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) ||
98 isa<LoadInst>(I)) // Don't inline a load across a store!
101 // Only inline instruction it it's use is in the same BB as the inst.
102 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
105 // Instruction visitation functions
106 friend class InstVisitor<CWriter>;
108 void visitReturnInst(ReturnInst &I);
109 void visitBranchInst(BranchInst &I);
111 void visitPHINode(PHINode &I) {}
112 void visitBinaryOperator(Instruction &I);
114 void visitCastInst (CastInst &I);
115 void visitCallInst (CallInst &I);
116 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
118 void visitMallocInst(MallocInst &I);
119 void visitAllocaInst(AllocaInst &I);
120 void visitFreeInst (FreeInst &I);
121 void visitLoadInst (LoadInst &I);
122 void visitStoreInst (StoreInst &I);
123 void visitGetElementPtrInst(GetElementPtrInst &I);
125 void visitInstruction(Instruction &I) {
126 std::cerr << "C Writer does not know about " << I;
130 void outputLValue(Instruction *I) {
131 Out << " " << getValueName(I) << " = ";
133 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
135 void printIndexingExpression(Value *Ptr, User::op_iterator I,
136 User::op_iterator E);
140 // We dont want identifier names with ., space, - in them.
141 // So we replace them with _
142 static string makeNameProper(string x) {
144 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
146 case '.': tmp += "d_"; break;
147 case ' ': tmp += "s_"; break;
148 case '-': tmp += "D_"; break;
155 string CWriter::getValueName(const Value *V) {
156 if (V->hasName()) { // Print out the label if it exists...
157 if (isa<GlobalValue>(V) && // Do not mangle globals...
158 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
159 !MangledGlobals.count(V)) // Unless the name would collide if we don't
160 return makeNameProper(V->getName());
162 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
163 makeNameProper(V->getName());
166 int Slot = Table->getValSlot(V);
167 assert(Slot >= 0 && "Invalid value!");
168 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
171 // A pointer type should not use parens around *'s alone, e.g., (**)
172 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
173 return (NameSoFar.find_last_not_of('*') != std::string::npos);
176 // Pass the Type* and the variable name and this prints out the variable
179 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
180 bool IgnoreName, bool namedContext) {
181 if (Ty->isPrimitiveType())
182 switch (Ty->getPrimitiveID()) {
183 case Type::VoidTyID: return Out << "void " << NameSoFar;
184 case Type::BoolTyID: return Out << "bool " << NameSoFar;
185 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
186 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
187 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
188 case Type::ShortTyID: return Out << "short " << NameSoFar;
189 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
190 case Type::IntTyID: return Out << "int " << NameSoFar;
191 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
192 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
193 case Type::FloatTyID: return Out << "float " << NameSoFar;
194 case Type::DoubleTyID: return Out << "double " << NameSoFar;
196 std::cerr << "Unknown primitive type: " << Ty << "\n";
200 // Check to see if the type is named.
201 if (!IgnoreName || isa<OpaqueType>(Ty)) {
202 map<const Type *, string>::iterator I = TypeNames.find(Ty);
203 if (I != TypeNames.end()) {
204 return Out << I->second << " " << NameSoFar;
208 switch (Ty->getPrimitiveID()) {
209 case Type::FunctionTyID: {
210 const FunctionType *MTy = cast<FunctionType>(Ty);
211 printType(MTy->getReturnType(), "");
212 Out << " (" << NameSoFar << ") (";
214 for (FunctionType::ParamTypes::const_iterator
215 I = MTy->getParamTypes().begin(),
216 E = MTy->getParamTypes().end(); I != E; ++I) {
217 if (I != MTy->getParamTypes().begin())
221 if (MTy->isVarArg()) {
222 if (!MTy->getParamTypes().empty())
228 case Type::StructTyID: {
229 const StructType *STy = cast<StructType>(Ty);
230 Out << NameSoFar + " {\n";
232 for (StructType::ElementTypes::const_iterator
233 I = STy->getElementTypes().begin(),
234 E = STy->getElementTypes().end(); I != E; ++I) {
236 printType(*I, "field" + utostr(Idx++));
242 case Type::PointerTyID: {
243 const PointerType *PTy = cast<PointerType>(Ty);
244 std::string ptrName = "*" + NameSoFar;
246 // Do not need parens around "* NameSoFar" if NameSoFar consists only
247 // of zero or more '*' chars *and* this is not an unnamed pointer type
248 // such as the result type in a cast statement. Otherwise, enclose in ( ).
249 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
250 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
251 ptrName = "(" + ptrName + ")"; //
253 return printType(PTy->getElementType(), ptrName);
256 case Type::ArrayTyID: {
257 const ArrayType *ATy = cast<ArrayType>(Ty);
258 unsigned NumElements = ATy->getNumElements();
259 return printType(ATy->getElementType(),
260 NameSoFar + "[" + utostr(NumElements) + "]");
263 case Type::OpaqueTyID: {
264 static int Count = 0;
265 string TyName = "struct opaque_" + itostr(Count++);
266 assert(TypeNames.find(Ty) == TypeNames.end());
267 TypeNames[Ty] = TyName;
268 return Out << TyName << " " << NameSoFar;
271 assert(0 && "Unhandled case in getTypeProps!");
278 void CWriter::printConstantArray(ConstantArray *CPA) {
280 // As a special case, print the array as a string if it is an array of
281 // ubytes or an array of sbytes with positive values.
283 const Type *ETy = CPA->getType()->getElementType();
284 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
286 // Make sure the last character is a null char, as automatically added by C
287 if (CPA->getNumOperands() == 0 ||
288 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
293 // Do not include the last character, which we know is null
294 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
295 unsigned char C = (ETy == Type::SByteTy) ?
296 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
297 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
300 if (C == '"' || C == '\\')
306 case '\n': Out << "\\n"; break;
307 case '\t': Out << "\\t"; break;
308 case '\r': Out << "\\r"; break;
309 case '\v': Out << "\\v"; break;
310 case '\a': Out << "\\a"; break;
311 case '\"': Out << "\\\""; break;
312 case '\'': Out << "\\\'"; break;
315 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
316 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
324 if (CPA->getNumOperands()) {
326 printConstant(cast<Constant>(CPA->getOperand(0)));
327 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
329 printConstant(cast<Constant>(CPA->getOperand(i)));
337 // printConstant - The LLVM Constant to C Constant converter.
338 void CWriter::printConstant(Constant *CPV) {
339 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
340 switch (CE->getOpcode()) {
341 case Instruction::Cast:
343 printType(CPV->getType());
345 printConstant(cast<Constant>(CPV->getOperand(0)));
349 case Instruction::GetElementPtr:
351 printIndexingExpression(CPV->getOperand(0),
352 CPV->op_begin()+1, CPV->op_end());
355 case Instruction::Add:
357 printConstant(cast<Constant>(CPV->getOperand(0)));
359 printConstant(cast<Constant>(CPV->getOperand(1)));
362 case Instruction::Sub:
364 printConstant(cast<Constant>(CPV->getOperand(0)));
366 printConstant(cast<Constant>(CPV->getOperand(1)));
371 std::cerr << "CWriter Error: Unhandled constant expression: "
377 switch (CPV->getType()->getPrimitiveID()) {
379 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
380 case Type::SByteTyID:
381 case Type::ShortTyID:
383 Out << cast<ConstantSInt>(CPV)->getValue(); break;
385 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
387 case Type::UByteTyID:
388 case Type::UShortTyID:
389 Out << cast<ConstantUInt>(CPV)->getValue(); break;
391 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
392 case Type::ULongTyID:
393 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
395 case Type::FloatTyID:
396 case Type::DoubleTyID: {
397 ConstantFP *FPC = cast<ConstantFP>(CPV);
398 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
399 if (I != FPConstantMap.end()) {
400 // Because of FP precision problems we must load from a stack allocated
401 // value that holds the value in hex.
402 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
403 << "*)&FloatConstant" << I->second << ")";
405 Out << FPC->getValue();
410 case Type::ArrayTyID:
411 printConstantArray(cast<ConstantArray>(CPV));
414 case Type::StructTyID: {
416 if (CPV->getNumOperands()) {
418 printConstant(cast<Constant>(CPV->getOperand(0)));
419 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
421 printConstant(cast<Constant>(CPV->getOperand(i)));
428 case Type::PointerTyID:
429 if (isa<ConstantPointerNull>(CPV)) {
432 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
433 writeOperand(CPR->getValue());
438 std::cerr << "Unknown constant type: " << CPV << "\n";
443 void CWriter::writeOperandInternal(Value *Operand) {
444 if (Instruction *I = dyn_cast<Instruction>(Operand))
445 if (isInlinableInst(*I)) {
446 // Should we inline this instruction to build a tree?
453 if (Operand->hasName()) {
454 Out << getValueName(Operand);
455 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
458 int Slot = Table->getValSlot(Operand);
459 assert(Slot >= 0 && "Malformed LLVM!");
460 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
464 void CWriter::writeOperand(Value *Operand) {
465 if (isa<GlobalVariable>(Operand))
466 Out << "(&"; // Global variables are references as their addresses by llvm
468 writeOperandInternal(Operand);
470 if (isa<GlobalVariable>(Operand))
474 // nameAllUsedStructureTypes - If there are structure types in the module that
475 // are used but do not have names assigned to them in the symbol table yet then
476 // we assign them names now.
478 bool CWriter::nameAllUsedStructureTypes(Module &M) {
479 // Get a set of types that are used by the program...
480 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
482 // Loop over the module symbol table, removing types from UT that are already
485 SymbolTable *MST = M.getSymbolTableSure();
486 if (MST->find(Type::TypeTy) != MST->end())
487 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
488 E = MST->type_end(Type::TypeTy); I != E; ++I)
489 UT.erase(cast<Type>(I->second));
491 // UT now contains types that are not named. Loop over it, naming structure
494 bool Changed = false;
495 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
497 if (const StructType *ST = dyn_cast<StructType>(*I)) {
498 ((Value*)ST)->setName("unnamed", MST);
504 void CWriter::printModule(Module *M) {
505 // Calculate which global values have names that will collide when we throw
506 // away type information.
507 { // Scope to delete the FoundNames set when we are done with it...
508 std::set<string> FoundNames;
509 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
510 if (I->hasName()) // If the global has a name...
511 if (FoundNames.count(I->getName())) // And the name is already used
512 MangledGlobals.insert(I); // Mangle the name
514 FoundNames.insert(I->getName()); // Otherwise, keep track of name
516 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
517 if (I->hasName()) // If the global has a name...
518 if (FoundNames.count(I->getName())) // And the name is already used
519 MangledGlobals.insert(I); // Mangle the name
521 FoundNames.insert(I->getName()); // Otherwise, keep track of name
524 // printing stdlib inclusion
525 //Out << "#include <stdlib.h>\n";
527 // get declaration for alloca
528 Out << "/* Provide Declarations */\n"
529 << "#include <alloca.h>\n\n"
531 // Provide a definition for null if one does not already exist,
532 // and for `bool' if not compiling with a C++ compiler.
533 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
534 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
536 << "\n\n/* Support for floating point constants */\n"
537 << "typedef unsigned long long ConstantDoubleTy;\n"
539 << "\n\n/* Global Declarations */\n";
541 // First output all the declarations for the program, because C requires
542 // Functions & globals to be declared before they are used.
545 // Loop over the symbol table, emitting all named constants...
546 if (M->hasSymbolTable())
547 printSymbolTable(*M->getSymbolTable());
549 // Global variable declarations...
551 Out << "\n/* External Global Variable Declarations */\n";
552 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
553 if (I->hasExternalLinkage()) {
555 printType(I->getType()->getElementType(), getValueName(I));
561 // Function declarations
563 Out << "\n/* Function Declarations */\n";
565 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
566 printFunctionSignature(I, true);
571 // Print Malloc prototype if needed
573 Out << "\n/* Malloc to make sun happy */\n";
574 Out << "extern void * malloc(size_t);\n\n";
577 // Output the global variable declerations
579 Out << "\n\n/* Global Variable Declerations */\n";
580 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
581 if (!I->isExternal()) {
583 printType(I->getType()->getElementType(), getValueName(I));
590 // Output the global variable definitions and contents...
592 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
593 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
594 if (!I->isExternal()) {
595 if (I->hasInternalLinkage())
597 printType(I->getType()->getElementType(), getValueName(I));
600 writeOperand(I->getInitializer());
605 // Output all of the functions...
607 Out << "\n\n/* Function Bodies */\n";
608 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
614 /// printSymbolTable - Run through symbol table looking for type names. If a
615 /// type name is found, emit it's declaration...
617 void CWriter::printSymbolTable(const SymbolTable &ST) {
618 // If there are no type names, exit early.
619 if (ST.find(Type::TypeTy) == ST.end())
622 // We are only interested in the type plane of the symbol table...
623 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
624 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
626 // Print out forward declarations for structure types before anything else!
627 Out << "/* Structure forward decls */\n";
628 for (; I != End; ++I)
629 if (const Type *STy = dyn_cast<StructType>(I->second)) {
630 string Name = "struct l_" + makeNameProper(I->first);
631 Out << Name << ";\n";
632 TypeNames.insert(std::make_pair(STy, Name));
637 // Now we can print out typedefs...
638 Out << "/* Typedefs */\n";
639 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
640 const Type *Ty = cast<Type>(I->second);
641 string Name = "l_" + makeNameProper(I->first);
649 // Keep track of which structures have been printed so far...
650 std::set<const StructType *> StructPrinted;
652 // Loop over all structures then push them into the stack so they are
653 // printed in the correct order.
655 Out << "/* Structure contents */\n";
656 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
657 if (const StructType *STy = dyn_cast<StructType>(I->second))
658 printContainedStructs(STy, StructPrinted);
661 // Push the struct onto the stack and recursively push all structs
662 // this one depends on.
663 void CWriter::printContainedStructs(const Type *Ty,
664 std::set<const StructType*> &StructPrinted){
665 if (const StructType *STy = dyn_cast<StructType>(Ty)){
666 //Check to see if we have already printed this struct
667 if (StructPrinted.count(STy) == 0) {
668 // Print all contained types first...
669 for (StructType::ElementTypes::const_iterator
670 I = STy->getElementTypes().begin(),
671 E = STy->getElementTypes().end(); I != E; ++I) {
672 const Type *Ty1 = I->get();
673 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
674 printContainedStructs(Ty1, StructPrinted);
677 //Print structure type out..
678 StructPrinted.insert(STy);
679 string Name = TypeNames[STy];
680 printType(STy, Name, true);
684 // If it is an array, check contained types and continue
685 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
686 const Type *Ty1 = ATy->getElementType();
687 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
688 printContainedStructs(Ty1, StructPrinted);
693 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
694 // If the program provides it's own malloc prototype we don't need
695 // to include the general one.
696 if (getValueName(F) == "malloc")
698 if (F->hasInternalLinkage()) Out << "static ";
700 // Loop over the arguments, printing them...
701 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
703 // Print out the return type and name...
704 printType(F->getReturnType());
705 Out << getValueName(F) << "(";
707 if (!F->isExternal()) {
710 if (F->abegin()->hasName() || !Prototype)
711 ArgName = getValueName(F->abegin());
713 printType(F->afront().getType(), ArgName);
715 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
718 if (I->hasName() || !Prototype)
719 ArgName = getValueName(I);
722 printType(I->getType(), ArgName);
726 // Loop over the arguments, printing them...
727 for (FunctionType::ParamTypes::const_iterator I =
728 FT->getParamTypes().begin(),
729 E = FT->getParamTypes().end(); I != E; ++I) {
730 if (I != FT->getParamTypes().begin()) Out << ", ";
735 // Finish printing arguments... if this is a vararg function, print the ...,
736 // unless there are no known types, in which case, we just emit ().
738 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
739 if (FT->getParamTypes().size()) Out << ", ";
740 Out << "..."; // Output varargs portion of signature!
746 void CWriter::printFunction(Function *F) {
747 if (F->isExternal()) return;
749 Table->incorporateFunction(F);
751 printFunctionSignature(F, false);
754 // print local variable information for the function
755 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
756 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
758 printType((*I)->getType(), getValueName(*I));
764 // Scan the function for floating point constants. If any FP constant is used
765 // in the function, we want to redirect it here so that we do not depend on
766 // the precision of the printed form.
768 unsigned FPCounter = 0;
769 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
770 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
771 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
772 double Val = FPC->getValue();
774 FPConstantMap[FPC] = FPCounter; // Number the FP constants
775 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
776 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
777 << "; /* " << Val << " */\n";
782 // print the basic blocks
783 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
784 BasicBlock *Prev = BB->getPrev();
786 // Don't print the label for the basic block if there are no uses, or if the
787 // only terminator use is the precessor basic block's terminator. We have
788 // to scan the use list because PHI nodes use basic blocks too but do not
789 // require a label to be generated.
791 bool NeedsLabel = false;
792 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
794 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
795 if (TI != Prev->getTerminator()) {
800 if (NeedsLabel) Out << getValueName(BB) << ":\n";
802 // Output all of the instructions in the basic block...
803 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
804 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
805 if (II->getType() != Type::VoidTy)
814 // Don't emit prefix or suffix for the terminator...
815 visit(*BB->getTerminator());
819 Table->purgeFunction();
820 FPConstantMap.clear();
823 // Specific Instruction type classes... note that all of the casts are
824 // neccesary because we use the instruction classes as opaque types...
826 void CWriter::visitReturnInst(ReturnInst &I) {
827 // Don't output a void return if this is the last basic block in the function
828 if (I.getNumOperands() == 0 &&
829 &*--I.getParent()->getParent()->end() == I.getParent() &&
830 !I.getParent()->size() == 1) {
835 if (I.getNumOperands()) {
837 writeOperand(I.getOperand(0));
842 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
843 // If PHI nodes need copies, we need the copy code...
844 if (isa<PHINode>(To->front()) ||
845 From->getNext() != To) // Not directly successor, need goto
848 // Otherwise we don't need the code.
852 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
854 for (BasicBlock::iterator I = Succ->begin();
855 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
856 // now we have to do the printing
857 Out << string(Indent, ' ');
859 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
860 Out << "; /* for PHI node */\n";
863 if (CurBB->getNext() != Succ) {
864 Out << string(Indent, ' ') << " goto ";
870 // Brach instruction printing - Avoid printing out a brach to a basic block that
871 // immediately succeeds the current one.
873 void CWriter::visitBranchInst(BranchInst &I) {
874 if (I.isConditional()) {
875 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
877 writeOperand(I.getCondition());
880 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
882 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
883 Out << " } else {\n";
884 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
887 // First goto not neccesary, assume second one is...
889 writeOperand(I.getCondition());
892 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
897 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
903 void CWriter::visitBinaryOperator(Instruction &I) {
904 // binary instructions, shift instructions, setCond instructions.
905 if (isa<PointerType>(I.getType())) {
907 printType(I.getType());
911 if (isa<PointerType>(I.getType())) Out << "(long long)";
912 writeOperand(I.getOperand(0));
914 switch (I.getOpcode()) {
915 case Instruction::Add: Out << " + "; break;
916 case Instruction::Sub: Out << " - "; break;
917 case Instruction::Mul: Out << "*"; break;
918 case Instruction::Div: Out << "/"; break;
919 case Instruction::Rem: Out << "%"; break;
920 case Instruction::And: Out << " & "; break;
921 case Instruction::Or: Out << " | "; break;
922 case Instruction::Xor: Out << " ^ "; break;
923 case Instruction::SetEQ: Out << " == "; break;
924 case Instruction::SetNE: Out << " != "; break;
925 case Instruction::SetLE: Out << " <= "; break;
926 case Instruction::SetGE: Out << " >= "; break;
927 case Instruction::SetLT: Out << " < "; break;
928 case Instruction::SetGT: Out << " > "; break;
929 case Instruction::Shl : Out << " << "; break;
930 case Instruction::Shr : Out << " >> "; break;
931 default: std::cerr << "Invalid operator type!" << I; abort();
934 if (isa<PointerType>(I.getType())) Out << "(long long)";
935 writeOperand(I.getOperand(1));
938 void CWriter::visitCastInst(CastInst &I) {
940 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
942 writeOperand(I.getOperand(0));
945 void CWriter::visitCallInst(CallInst &I) {
946 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
947 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
948 const Type *RetTy = FTy->getReturnType();
950 writeOperand(I.getOperand(0));
953 if (I.getNumOperands() > 1) {
954 writeOperand(I.getOperand(1));
956 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
958 writeOperand(I.getOperand(op));
964 void CWriter::visitMallocInst(MallocInst &I) {
966 printType(I.getType());
967 Out << ")malloc(sizeof(";
968 printType(I.getType()->getElementType());
971 if (I.isArrayAllocation()) {
973 writeOperand(I.getOperand(0));
978 void CWriter::visitAllocaInst(AllocaInst &I) {
980 printType(I.getType());
981 Out << ") alloca(sizeof(";
982 printType(I.getType()->getElementType());
984 if (I.isArrayAllocation()) {
986 writeOperand(I.getOperand(0));
991 void CWriter::visitFreeInst(FreeInst &I) {
993 writeOperand(I.getOperand(0));
997 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
998 User::op_iterator E) {
999 bool HasImplicitAddress = false;
1000 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1001 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1002 HasImplicitAddress = true;
1003 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1004 HasImplicitAddress = true;
1005 Ptr = CPR->getValue(); // Get to the global...
1009 if (!HasImplicitAddress)
1010 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1012 writeOperandInternal(Ptr);
1016 const Constant *CI = dyn_cast<Constant>(I->get());
1017 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1020 writeOperandInternal(Ptr);
1022 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1024 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1027 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1028 "Can only have implicit address with direct accessing");
1030 if (HasImplicitAddress) {
1032 } else if (CI && CI->isNullValue() && I+1 != E) {
1033 // Print out the -> operator if possible...
1034 if ((*(I+1))->getType() == Type::UByteTy) {
1035 Out << (HasImplicitAddress ? "." : "->");
1036 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1042 if ((*I)->getType() == Type::LongTy) {
1047 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1051 void CWriter::visitLoadInst(LoadInst &I) {
1053 writeOperand(I.getOperand(0));
1056 void CWriter::visitStoreInst(StoreInst &I) {
1058 writeOperand(I.getPointerOperand());
1060 writeOperand(I.getOperand(0));
1063 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1065 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1068 //===----------------------------------------------------------------------===//
1069 // External Interface declaration
1070 //===----------------------------------------------------------------------===//
1072 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }