1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
5 // TODO : Recursive types.
7 //===-----------------------------------------------------------------------==//
9 #include "llvm/Assembly/CWriter.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Module.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/iPHINode.h"
16 #include "llvm/iOther.h"
17 #include "llvm/iOperators.h"
18 #include "llvm/Pass.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/SlotCalculator.h"
21 #include "llvm/Analysis/FindUsedTypes.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Support/InstIterator.h"
24 #include "Support/StringExtras.h"
25 #include "Support/STLExtras.h"
33 class CWriter : public Pass, public InstVisitor<CWriter> {
35 SlotCalculator *Table;
36 const Module *TheModule;
37 map<const Type *, string> TypeNames;
38 std::set<const Value*> MangledGlobals;
40 CWriter(ostream &o) : Out(o) {}
42 void getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addRequired<FindUsedTypes>();
47 virtual bool run(Module &M) {
49 Table = new SlotCalculator(&M, false);
52 // Ensure that all structure types have names...
53 bool Changed = nameAllUsedStructureTypes(M);
61 MangledGlobals.clear();
65 ostream &printType(const Type *Ty, const string &VariableName = "",
66 bool IgnoreName = false, bool namedContext = true);
68 void writeOperand(Value *Operand);
69 void writeOperandInternal(Value *Operand);
71 string getValueName(const Value *V);
74 bool nameAllUsedStructureTypes(Module &M);
75 void printModule(Module *M);
76 void printSymbolTable(const SymbolTable &ST);
77 void printGlobal(const GlobalVariable *GV);
78 void printFunctionSignature(const Function *F, bool Prototype);
80 void printFunction(Function *);
82 void printConstant(Constant *CPV);
83 void printConstantArray(ConstantArray *CPA);
85 // isInlinableInst - Attempt to inline instructions into their uses to build
86 // trees as much as possible. To do this, we have to consistently decide
87 // what is acceptable to inline, so that variable declarations don't get
88 // printed and an extra copy of the expr is not emitted.
90 static bool isInlinableInst(const Instruction &I) {
91 // Must be an expression, must be used exactly once. If it is dead, we
92 // emit it inline where it would go.
93 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
94 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
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);
107 void visitPHINode(PHINode &I) {}
108 void visitBinaryOperator(Instruction &I);
110 void visitCastInst (CastInst &I);
111 void visitCallInst (CallInst &I);
112 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
114 void visitMallocInst(MallocInst &I);
115 void visitAllocaInst(AllocaInst &I);
116 void visitFreeInst (FreeInst &I);
117 void visitLoadInst (LoadInst &I);
118 void visitStoreInst (StoreInst &I);
119 void visitGetElementPtrInst(GetElementPtrInst &I);
121 void visitInstruction(Instruction &I) {
122 std::cerr << "C Writer does not know about " << I;
126 void outputLValue(Instruction *I) {
127 Out << " " << getValueName(I) << " = ";
129 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
131 void printIndexingExpression(Value *Ptr, User::op_iterator I,
132 User::op_iterator E);
136 // We dont want identifier names with ., space, - in them.
137 // So we replace them with _
138 static string makeNameProper(string x) {
140 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
142 case '.': tmp += "d_"; break;
143 case ' ': tmp += "s_"; break;
144 case '-': tmp += "D_"; break;
151 string CWriter::getValueName(const Value *V) {
152 if (V->hasName()) { // Print out the label if it exists...
153 if (isa<GlobalValue>(V) && // Do not mangle globals...
154 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
155 !MangledGlobals.count(V)) // Unless the name would collide if we don't
156 return makeNameProper(V->getName());
158 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
159 makeNameProper(V->getName());
162 int Slot = Table->getValSlot(V);
163 assert(Slot >= 0 && "Invalid value!");
164 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
167 // A pointer type should not use parens around *'s alone, e.g., (**)
168 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
169 return (NameSoFar.find_last_not_of('*') != std::string::npos);
172 // Pass the Type* and the variable name and this prints out the variable
175 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
176 bool IgnoreName, bool namedContext) {
177 if (Ty->isPrimitiveType())
178 switch (Ty->getPrimitiveID()) {
179 case Type::VoidTyID: return Out << "void " << NameSoFar;
180 case Type::BoolTyID: return Out << "bool " << NameSoFar;
181 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
182 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
183 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
184 case Type::ShortTyID: return Out << "short " << NameSoFar;
185 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
186 case Type::IntTyID: return Out << "int " << NameSoFar;
187 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
188 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
189 case Type::FloatTyID: return Out << "float " << NameSoFar;
190 case Type::DoubleTyID: return Out << "double " << NameSoFar;
192 std::cerr << "Unknown primitive type: " << Ty << "\n";
196 // Check to see if the type is named.
198 map<const Type *, string>::iterator I = TypeNames.find(Ty);
199 if (I != TypeNames.end()) {
200 return Out << I->second << " " << NameSoFar;
204 switch (Ty->getPrimitiveID()) {
205 case Type::FunctionTyID: {
206 const FunctionType *MTy = cast<FunctionType>(Ty);
207 printType(MTy->getReturnType(), "");
208 Out << " " << NameSoFar << " (";
210 for (FunctionType::ParamTypes::const_iterator
211 I = MTy->getParamTypes().begin(),
212 E = MTy->getParamTypes().end(); I != E; ++I) {
213 if (I != MTy->getParamTypes().begin())
217 if (MTy->isVarArg()) {
218 if (!MTy->getParamTypes().empty())
224 case Type::StructTyID: {
225 const StructType *STy = cast<StructType>(Ty);
226 Out << NameSoFar + " {\n";
228 for (StructType::ElementTypes::const_iterator
229 I = STy->getElementTypes().begin(),
230 E = STy->getElementTypes().end(); I != E; ++I) {
232 printType(*I, "field" + utostr(Idx++));
238 case Type::PointerTyID: {
239 const PointerType *PTy = cast<PointerType>(Ty);
240 std::string ptrName = "*" + NameSoFar;
242 // Do not need parens around "* NameSoFar" if NameSoFar consists only
243 // of zero or more '*' chars *and* this is not an unnamed pointer type
244 // such as the result type in a cast statement. Otherwise, enclose in ( ).
245 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext)
246 ptrName = "(" + ptrName + ")"; //
248 return printType(PTy->getElementType(), ptrName);
251 case Type::ArrayTyID: {
252 const ArrayType *ATy = cast<ArrayType>(Ty);
253 unsigned NumElements = ATy->getNumElements();
254 return printType(ATy->getElementType(),
255 NameSoFar + "[" + utostr(NumElements) + "]");
258 assert(0 && "Unhandled case in getTypeProps!");
265 void CWriter::printConstantArray(ConstantArray *CPA) {
267 // As a special case, print the array as a string if it is an array of
268 // ubytes or an array of sbytes with positive values.
270 const Type *ETy = CPA->getType()->getElementType();
271 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
273 // Make sure the last character is a null char, as automatically added by C
274 if (CPA->getNumOperands() == 0 ||
275 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
280 // Do not include the last character, which we know is null
281 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
282 unsigned char C = (ETy == Type::SByteTy) ?
283 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
284 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
290 case '\n': Out << "\\n"; break;
291 case '\t': Out << "\\t"; break;
292 case '\r': Out << "\\r"; break;
293 case '\v': Out << "\\v"; break;
294 case '\a': Out << "\\a"; break;
297 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
298 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
306 if (CPA->getNumOperands()) {
308 printConstant(cast<Constant>(CPA->getOperand(0)));
309 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
311 printConstant(cast<Constant>(CPA->getOperand(i)));
319 // printConstant - The LLVM Constant to C Constant converter.
320 void CWriter::printConstant(Constant *CPV) {
321 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
322 switch (CE->getOpcode()) {
323 case Instruction::Cast:
325 printType(CPV->getType());
327 printConstant(cast<Constant>(CPV->getOperand(0)));
331 case Instruction::GetElementPtr:
333 printIndexingExpression(CPV->getOperand(0),
334 CPV->op_begin()+1, CPV->op_end());
337 case Instruction::Add:
339 printConstant(cast<Constant>(CPV->getOperand(0)));
341 printConstant(cast<Constant>(CPV->getOperand(1)));
344 case Instruction::Sub:
346 printConstant(cast<Constant>(CPV->getOperand(0)));
348 printConstant(cast<Constant>(CPV->getOperand(1)));
353 std::cerr << "CWriter Error: Unhandled constant expression: "
359 switch (CPV->getType()->getPrimitiveID()) {
361 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
362 case Type::SByteTyID:
363 case Type::ShortTyID:
365 Out << cast<ConstantSInt>(CPV)->getValue(); break;
367 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
369 case Type::UByteTyID:
370 case Type::UShortTyID:
371 Out << cast<ConstantUInt>(CPV)->getValue(); break;
373 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
374 case Type::ULongTyID:
375 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
377 case Type::FloatTyID:
378 case Type::DoubleTyID:
379 Out << cast<ConstantFP>(CPV)->getValue(); break;
381 case Type::ArrayTyID:
382 printConstantArray(cast<ConstantArray>(CPV));
385 case Type::StructTyID: {
387 if (CPV->getNumOperands()) {
389 printConstant(cast<Constant>(CPV->getOperand(0)));
390 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
392 printConstant(cast<Constant>(CPV->getOperand(i)));
399 case Type::PointerTyID:
400 if (isa<ConstantPointerNull>(CPV)) {
402 printType(CPV->getType(), "");
405 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
406 writeOperand(CPR->getValue());
411 std::cerr << "Unknown constant type: " << CPV << "\n";
416 void CWriter::writeOperandInternal(Value *Operand) {
417 if (Instruction *I = dyn_cast<Instruction>(Operand))
418 if (isInlinableInst(*I)) {
419 // Should we inline this instruction to build a tree?
426 if (Operand->hasName()) {
427 Out << getValueName(Operand);
428 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
431 int Slot = Table->getValSlot(Operand);
432 assert(Slot >= 0 && "Malformed LLVM!");
433 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
437 void CWriter::writeOperand(Value *Operand) {
438 if (isa<GlobalVariable>(Operand))
439 Out << "(&"; // Global variables are references as their addresses by llvm
441 writeOperandInternal(Operand);
443 if (isa<GlobalVariable>(Operand))
447 // nameAllUsedStructureTypes - If there are structure types in the module that
448 // are used but do not have names assigned to them in the symbol table yet then
449 // we assign them names now.
451 bool CWriter::nameAllUsedStructureTypes(Module &M) {
452 // Get a set of types that are used by the program...
453 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
455 // Loop over the module symbol table, removing types from UT that are already
458 SymbolTable *MST = M.getSymbolTableSure();
459 if (MST->find(Type::TypeTy) != MST->end())
460 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
461 E = MST->type_end(Type::TypeTy); I != E; ++I)
462 UT.erase(cast<Type>(I->second));
464 // UT now contains types that are not named. Loop over it, naming structure
467 bool Changed = false;
468 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
470 if (const StructType *ST = dyn_cast<StructType>(*I)) {
471 ((Value*)ST)->setName("unnamed", MST);
477 void CWriter::printModule(Module *M) {
478 // Calculate which global values have names that will collide when we throw
479 // away type information.
480 { // Scope to delete the FoundNames set when we are done with it...
481 std::set<string> FoundNames;
482 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
483 if (I->hasName()) // If the global has a name...
484 if (FoundNames.count(I->getName())) // And the name is already used
485 MangledGlobals.insert(I); // Mangle the name
487 FoundNames.insert(I->getName()); // Otherwise, keep track of name
489 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
490 if (I->hasName()) // If the global has a name...
491 if (FoundNames.count(I->getName())) // And the name is already used
492 MangledGlobals.insert(I); // Mangle the name
494 FoundNames.insert(I->getName()); // Otherwise, keep track of name
497 // printing stdlib inclusion
498 // Out << "#include <stdlib.h>\n";
500 // get declaration for alloca
501 Out << "/* Provide Declarations */\n"
502 << "#include <malloc.h>\n"
503 << "#include <alloca.h>\n\n"
505 // Provide a definition for null if one does not already exist,
506 // and for `bool' if not compiling with a C++ compiler.
507 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
508 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
510 << "\n\n/* Global Declarations */\n";
512 // First output all the declarations for the program, because C requires
513 // Functions & globals to be declared before they are used.
516 // Loop over the symbol table, emitting all named constants...
517 if (M->hasSymbolTable())
518 printSymbolTable(*M->getSymbolTable());
520 // Global variable declarations...
522 Out << "\n/* Global Variable Declarations */\n";
523 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
524 Out << (I->hasExternalLinkage() ? "extern " : "static ");
525 printType(I->getType()->getElementType(), getValueName(I));
530 // Function declarations
532 Out << "\n/* Function Declarations */\n";
533 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
534 printFunctionSignature(I, true);
539 // Output the global variable contents...
541 Out << "\n\n/* Global Data */\n";
542 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
543 if (I->hasInternalLinkage()) Out << "static ";
544 printType(I->getType()->getElementType(), getValueName(I));
546 if (I->hasInitializer()) {
548 writeOperand(I->getInitializer());
554 // Output all of the functions...
556 Out << "\n\n/* Function Bodies */\n";
557 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
563 // printSymbolTable - Run through symbol table looking for named constants
564 // if a named constant is found, emit it's declaration...
565 // Assuming that symbol table has only types and constants.
566 void CWriter::printSymbolTable(const SymbolTable &ST) {
567 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
568 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
569 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
571 for (; I != End; ++I)
572 if (const Type *Ty = dyn_cast<StructType>(I->second)) {
573 string Name = "struct l_" + makeNameProper(I->first);
574 Out << Name << ";\n";
575 TypeNames.insert(std::make_pair(Ty, Name));
581 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
582 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
583 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
585 for (; I != End; ++I) {
586 const Value *V = I->second;
587 if (const Type *Ty = dyn_cast<Type>(V)) {
588 string Name = "l_" + makeNameProper(I->first);
589 if (isa<StructType>(Ty))
590 Name = "struct " + makeNameProper(Name);
594 printType(Ty, Name, true);
602 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
603 if (F->hasInternalLinkage()) Out << "static ";
605 // Loop over the arguments, printing them...
606 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
608 // Print out the return type and name...
609 printType(F->getReturnType());
610 Out << getValueName(F) << "(";
612 if (!F->isExternal()) {
615 if (F->abegin()->hasName() || !Prototype)
616 ArgName = getValueName(F->abegin());
618 printType(F->afront().getType(), ArgName);
620 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
623 if (I->hasName() || !Prototype)
624 ArgName = getValueName(I);
627 printType(I->getType(), ArgName);
631 // Loop over the arguments, printing them...
632 for (FunctionType::ParamTypes::const_iterator I =
633 FT->getParamTypes().begin(),
634 E = FT->getParamTypes().end(); I != E; ++I) {
635 if (I != FT->getParamTypes().begin()) Out << ", ";
640 // Finish printing arguments...
641 if (FT->isVarArg()) {
642 if (FT->getParamTypes().size()) Out << ", ";
643 Out << "..."; // Output varargs portion of signature!
649 void CWriter::printFunction(Function *F) {
650 if (F->isExternal()) return;
652 Table->incorporateFunction(F);
654 printFunctionSignature(F, false);
657 // print local variable information for the function
658 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
659 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
661 printType((*I)->getType(), getValueName(*I));
665 // print the basic blocks
666 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
667 BasicBlock *Prev = BB->getPrev();
669 // Don't print the label for the basic block if there are no uses, or if the
670 // only terminator use is the precessor basic block's terminator. We have
671 // to scan the use list because PHI nodes use basic blocks too but do not
672 // require a label to be generated.
674 bool NeedsLabel = false;
675 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
677 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
678 if (TI != Prev->getTerminator()) {
683 if (NeedsLabel) Out << getValueName(BB) << ":\n";
685 // Output all of the instructions in the basic block...
686 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
687 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
688 if (II->getType() != Type::VoidTy)
697 // Don't emit prefix or suffix for the terminator...
698 visit(*BB->getTerminator());
702 Table->purgeFunction();
705 // Specific Instruction type classes... note that all of the casts are
706 // neccesary because we use the instruction classes as opaque types...
708 void CWriter::visitReturnInst(ReturnInst &I) {
709 // Don't output a void return if this is the last basic block in the function
710 if (I.getNumOperands() == 0 &&
711 &*--I.getParent()->getParent()->end() == I.getParent() &&
712 !I.getParent()->size() == 1) {
717 if (I.getNumOperands()) {
719 writeOperand(I.getOperand(0));
724 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
725 // If PHI nodes need copies, we need the copy code...
726 if (isa<PHINode>(To->front()) ||
727 From->getNext() != To) // Not directly successor, need goto
730 // Otherwise we don't need the code.
734 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
736 for (BasicBlock::iterator I = Succ->begin();
737 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
738 // now we have to do the printing
739 Out << string(Indent, ' ');
741 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
742 Out << "; /* for PHI node */\n";
745 if (CurBB->getNext() != Succ) {
746 Out << string(Indent, ' ') << " goto ";
752 // Brach instruction printing - Avoid printing out a brach to a basic block that
753 // immediately succeeds the current one.
755 void CWriter::visitBranchInst(BranchInst &I) {
756 if (I.isConditional()) {
757 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
759 writeOperand(I.getCondition());
762 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
764 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
765 Out << " } else {\n";
766 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
769 // First goto not neccesary, assume second one is...
771 writeOperand(I.getCondition());
774 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
779 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
785 void CWriter::visitBinaryOperator(Instruction &I) {
786 // binary instructions, shift instructions, setCond instructions.
787 if (isa<PointerType>(I.getType())) {
789 printType(I.getType());
793 if (isa<PointerType>(I.getType())) Out << "(long long)";
794 writeOperand(I.getOperand(0));
796 switch (I.getOpcode()) {
797 case Instruction::Add: Out << " + "; break;
798 case Instruction::Sub: Out << " - "; break;
799 case Instruction::Mul: Out << "*"; break;
800 case Instruction::Div: Out << "/"; break;
801 case Instruction::Rem: Out << "%"; break;
802 case Instruction::And: Out << " & "; break;
803 case Instruction::Or: Out << " | "; break;
804 case Instruction::Xor: Out << " ^ "; break;
805 case Instruction::SetEQ: Out << " == "; break;
806 case Instruction::SetNE: Out << " != "; break;
807 case Instruction::SetLE: Out << " <= "; break;
808 case Instruction::SetGE: Out << " >= "; break;
809 case Instruction::SetLT: Out << " < "; break;
810 case Instruction::SetGT: Out << " > "; break;
811 case Instruction::Shl : Out << " << "; break;
812 case Instruction::Shr : Out << " >> "; break;
813 default: std::cerr << "Invalid operator type!" << I; abort();
816 if (isa<PointerType>(I.getType())) Out << "(long long)";
817 writeOperand(I.getOperand(1));
820 void CWriter::visitCastInst(CastInst &I) {
822 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
824 writeOperand(I.getOperand(0));
827 void CWriter::visitCallInst(CallInst &I) {
828 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
829 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
830 const Type *RetTy = FTy->getReturnType();
832 writeOperand(I.getOperand(0));
835 if (I.getNumOperands() > 1) {
836 writeOperand(I.getOperand(1));
838 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
840 writeOperand(I.getOperand(op));
846 void CWriter::visitMallocInst(MallocInst &I) {
848 printType(I.getType());
849 Out << ")malloc(sizeof(";
850 printType(I.getType()->getElementType());
853 if (I.isArrayAllocation()) {
855 writeOperand(I.getOperand(0));
860 void CWriter::visitAllocaInst(AllocaInst &I) {
862 printType(I.getType());
863 Out << ") alloca(sizeof(";
864 printType(I.getType()->getElementType());
866 if (I.isArrayAllocation()) {
868 writeOperand(I.getOperand(0));
873 void CWriter::visitFreeInst(FreeInst &I) {
875 writeOperand(I.getOperand(0));
879 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
880 User::op_iterator E) {
881 bool HasImplicitAddress = false;
882 // If accessing a global value with no indexing, avoid *(&GV) syndrome
883 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
884 HasImplicitAddress = true;
885 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
886 HasImplicitAddress = true;
887 Ptr = CPR->getValue(); // Get to the global...
891 if (!HasImplicitAddress)
892 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
894 writeOperandInternal(Ptr);
898 const Constant *CI = dyn_cast<Constant>(I->get());
899 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
902 writeOperandInternal(Ptr);
904 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
907 // Print out the -> operator if possible...
908 if (CI && CI->isNullValue() && I+1 != E) {
909 if ((*(I+1))->getType() == Type::UByteTy) {
910 Out << (HasImplicitAddress ? "." : "->");
911 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
913 } else { // First array index of 0: Just skip it
919 if ((*I)->getType() == Type::LongTy) {
920 Out << "[((int) ("; // sign-extend from 32 (to 64) bits
923 printType(cast<PointerType>(Ptr->getType())->getElementType());
924 Out << "))) / sizeof(";
925 printType(cast<PointerType>(Ptr->getType())->getElementType());
928 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
932 void CWriter::visitLoadInst(LoadInst &I) {
934 writeOperand(I.getOperand(0));
937 void CWriter::visitStoreInst(StoreInst &I) {
939 writeOperand(I.getPointerOperand());
941 writeOperand(I.getOperand(0));
944 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
946 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
949 //===----------------------------------------------------------------------===//
950 // External Interface declaration
951 //===----------------------------------------------------------------------===//
953 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }