1 //===-- Writer.cpp - Library for writing C files --------------------------===//
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
6 // TODO : Recursive types.
8 //===-----------------------------------------------------------------------==//
10 #include "llvm/Assembly/CWriter.h"
11 #include "CLocalVars.h"
12 #include "llvm/SlotCalculator.h"
13 #include "llvm/Constants.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Module.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Function.h"
18 #include "llvm/Argument.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/iOther.h"
24 #include "llvm/iOperators.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "Support/StringExtras.h"
28 #include "Support/STLExtras.h"
37 //===-----------------------------------------------------------------------==//
39 // Implementation of the CLocalVars methods
41 // Appends a variable to the LocalVars map if it does not already exist
42 // Also check that the type exists on the map.
43 void CLocalVars::addLocalVar(const Type *t, const string & var) {
44 if (!LocalVars.count(t) ||
45 find(LocalVars[t].begin(), LocalVars[t].end(), var)
46 == LocalVars[t].end()) {
47 LocalVars[t].push_back(var);
51 static string calcTypeNameVar(const Type *Ty,
52 map<const Type *, string> &TypeNames,
53 string VariableName, string NameSoFar);
55 static std::string getConstStrValue(const Constant* CPV);
58 // We dont want identifier names with ., space, - in them.
59 // So we replace them with _
60 static string makeNameProper(string x) {
62 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++) {
75 static string getConstantName(const Constant *CPV) {
76 return CPV->getName();
80 static std::string getConstArrayStrValue(const Constant* CPV) {
83 // As a special case, print the array as a string if it is an array of
84 // ubytes or an array of sbytes with positive values.
86 const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
87 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
89 if (ETy == Type::SByteTy) {
90 for (unsigned i = 0; i < CPV->getNumOperands(); ++i)
91 if (ETy == Type::SByteTy &&
92 cast<ConstantSInt>(CPV->getOperand(i))->getValue() < 0) {
100 for (unsigned i = 0; i < CPV->getNumOperands(); ++i) {
101 unsigned char C = (ETy == Type::SByteTy) ?
102 (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
103 (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
109 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
110 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
117 if (CPV->getNumOperands()) {
118 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
119 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
120 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
128 static std::string getConstStructStrValue(const Constant* CPV) {
129 std::string Result = "{";
130 if (CPV->getNumOperands()) {
131 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
132 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
133 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
136 return Result + " }";
139 // our own getStrValue function for constant initializers
140 static std::string getConstStrValue(const Constant* CPV) {
141 // Does not handle null pointers, that needs to be checked explicitly
143 if (CPV == ConstantBool::False)
145 else if (CPV == ConstantBool::True)
148 else if (isa<ConstantArray>(CPV)) {
149 tempstr = getConstArrayStrValue(CPV);
151 else if (isa<ConstantStruct>(CPV)) {
152 tempstr = getConstStructStrValue(CPV);
154 else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CPV)) {
155 tempstr = utostr(CUI->getValue());
157 else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CPV)) {
158 tempstr = itostr(CSI->getValue());
160 else if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
161 tempstr = ftostr(CFP->getValue());
164 if (CPV->getType() == Type::ULongTy)
166 else if (CPV->getType() == Type::LongTy)
168 else if (CPV->getType() == Type::UIntTy ||
169 CPV->getType() == Type::UShortTy)
177 // Essentially pass the Type* variable, an empty typestack and this prints
179 static string calcTypeName(const Type *Ty, map<const Type *, string> &TypeNames,
180 string &FunctionInfo) {
182 // Takin' care of the fact that boolean would be int in C
183 // and that ushort would be unsigned short etc.
186 if (Ty->isPrimitiveType())
187 switch (Ty->getPrimitiveID()) {
188 case Type::VoidTyID: return "void";
189 case Type::BoolTyID: return "bool";
190 case Type::UByteTyID: return "unsigned char";
191 case Type::SByteTyID: return "signed char";
192 case Type::UShortTyID: return "unsigned short";
193 case Type::ShortTyID: return "short";
194 case Type::UIntTyID: return "unsigned";
195 case Type::IntTyID: return "int";
196 case Type::ULongTyID: return "unsigned long long";
197 case Type::LongTyID: return "signed long long";
198 case Type::FloatTyID: return "float";
199 case Type::DoubleTyID: return "double";
200 default : assert(0 && "Unknown primitive type!");
203 // Check to see if the type is named.
204 map<const Type *, string>::iterator I = TypeNames.find(Ty);
205 if (I != TypeNames.end())
210 switch (Ty->getPrimitiveID()) {
211 case Type::FunctionTyID: {
212 const FunctionType *MTy = cast<const FunctionType>(Ty);
213 Result = calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
215 Result += ") " + MInfo;
217 FunctionInfo += " (";
218 for (FunctionType::ParamTypes::const_iterator
219 I = MTy->getParamTypes().begin(),
220 E = MTy->getParamTypes().end(); I != E; ++I) {
221 if (I != MTy->getParamTypes().begin())
222 FunctionInfo += ", ";
224 FunctionInfo += calcTypeName(*I, TypeNames, MInfo);
226 Result += ") " + MInfo;
228 if (MTy->isVarArg()) {
229 if (!MTy->getParamTypes().empty())
230 FunctionInfo += ", ";
231 FunctionInfo += "...";
236 case Type::StructTyID: {
238 const StructType *STy = cast<const StructType>(Ty);
239 Result = " struct {\n ";
241 for (StructType::ElementTypes::const_iterator
242 I = STy->getElementTypes().begin(),
243 E = STy->getElementTypes().end(); I != E; ++I) {
244 Result += calcTypeNameVar(*I, TypeNames,
245 "field" + itostr(indx++), tempstr);
251 case Type::PointerTyID:
252 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
256 case Type::ArrayTyID: {
257 const ArrayType *ATy = cast<const ArrayType>(Ty);
258 int NumElements = ATy->getNumElements();
259 Result = calcTypeName(ATy->getElementType(), TypeNames, MInfo);
264 assert(0 && "Unhandled case in getTypeProps!");
272 // Pass the Type* variable and and the variable name and this prints out the
273 // variable declaration.
274 // This is different from calcTypeName because if you need to declare an array
275 // the size of the array would appear after the variable name itself
276 // For eg. int a[10];
277 static string calcTypeNameVar(const Type *Ty,
278 map<const Type *, string> &TypeNames,
279 string VariableName, string NameSoFar) {
280 if (Ty->isPrimitiveType())
281 switch (Ty->getPrimitiveID()) {
283 return "bool " + NameSoFar + VariableName;
284 case Type::UByteTyID:
285 return "unsigned char " + NameSoFar + VariableName;
286 case Type::SByteTyID:
287 return "signed char " + NameSoFar + VariableName;
288 case Type::UShortTyID:
289 return "unsigned long long " + NameSoFar + VariableName;
290 case Type::ULongTyID:
291 return "unsigned long long " + NameSoFar + VariableName;
293 return "signed long long " + NameSoFar + VariableName;
295 return "unsigned " + NameSoFar + VariableName;
297 return Ty->getDescription() + " " + NameSoFar + VariableName;
300 // Check to see if the type is named.
301 map<const Type *, string>::iterator I = TypeNames.find(Ty);
302 if (I != TypeNames.end())
303 return I->second + " " + NameSoFar + VariableName;
308 switch (Ty->getPrimitiveID()) {
309 case Type::FunctionTyID: {
311 const FunctionType *MTy = cast<const FunctionType>(Ty);
312 Result += calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
314 Result += ") " + MInfo;
315 Result += " " + NameSoFar + VariableName;
317 for (FunctionType::ParamTypes::const_iterator
318 I = MTy->getParamTypes().begin(),
319 E = MTy->getParamTypes().end(); I != E; ++I) {
320 if (I != MTy->getParamTypes().begin())
323 Result += calcTypeName(*I, TypeNames, MInfo);
325 Result += ") " + MInfo;
327 if (MTy->isVarArg()) {
328 if (!MTy->getParamTypes().empty())
335 case Type::StructTyID: {
336 const StructType *STy = cast<const StructType>(Ty);
337 Result = " struct {\n ";
339 for (StructType::ElementTypes::const_iterator
340 I = STy->getElementTypes().begin(),
341 E = STy->getElementTypes().end(); I != E; ++I) {
342 Result += calcTypeNameVar(*I, TypeNames,
343 "field" + itostr(indx++), "");
347 Result += " " + NameSoFar + VariableName;
351 case Type::PointerTyID: {
352 Result = calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(),
354 "(*" + NameSoFar + VariableName + ")");
358 case Type::ArrayTyID: {
359 const ArrayType *ATy = cast<const ArrayType>(Ty);
360 int NumElements = ATy->getNumElements();
361 Result = calcTypeNameVar(ATy->getElementType(), TypeNames,
362 tempstr, NameSoFar + VariableName + "[" +
363 itostr(NumElements) + "]");
367 assert(0 && "Unhandled case in getTypeProps!");
374 // printTypeVarInt - The internal guts of printing out a type that has a
375 // potentially named portion and the variable associated with the type.
376 static ostream &printTypeVarInt(ostream &Out, const Type *Ty,
377 map<const Type *, string> &TypeNames,
378 const string &VariableName) {
379 // Primitive types always print out their description, regardless of whether
380 // they have been named or not.
382 if (Ty->isPrimitiveType())
383 switch (Ty->getPrimitiveID()) {
385 return Out << "bool " << VariableName;
386 case Type::UByteTyID:
387 return Out << "unsigned char " << VariableName;
388 case Type::SByteTyID:
389 return Out << "signed char " << VariableName;
390 case Type::UShortTyID:
391 return Out << "unsigned long long " << VariableName;
392 case Type::ULongTyID:
393 return Out << "unsigned long long " << VariableName;
395 return Out << "signed long long " << VariableName;
397 return Out << "unsigned " << VariableName;
399 return Out << Ty->getDescription() << " " << VariableName;
402 // Check to see if the type is named.
403 map<const Type *, string>::iterator I = TypeNames.find(Ty);
404 if (I != TypeNames.end()) return Out << I->second << " " << VariableName;
406 // Otherwise we have a type that has not been named but is a derived type.
407 // Carefully recurse the type hierarchy to print out any contained symbolic
410 string TypeNameVar, tempstr = "";
411 TypeNameVar = calcTypeNameVar(Ty, TypeNames, VariableName, tempstr);
412 return Out << TypeNameVar;
415 // Internal guts of printing a type name
416 static ostream &printTypeInt(ostream &Out, const Type *Ty,
417 map<const Type *, string> &TypeNames) {
418 // Primitive types always print out their description, regardless of whether
419 // they have been named or not.
421 if (Ty->isPrimitiveType())
422 switch (Ty->getPrimitiveID()) {
424 return Out << "bool";
425 case Type::UByteTyID:
426 return Out << "unsigned char";
427 case Type::SByteTyID:
428 return Out << "signed char";
429 case Type::UShortTyID:
430 return Out << "unsigned short";
431 case Type::ULongTyID:
432 return Out << "unsigned long long";
434 return Out << "signed long long";
436 return Out << "unsigned";
438 return Out << Ty->getDescription();
441 // Check to see if the type is named.
442 map<const Type *, string>::iterator I = TypeNames.find(Ty);
443 if (I != TypeNames.end()) return Out << I->second;
445 // Otherwise we have a type that has not been named but is a derived type.
446 // Carefully recurse the type hierarchy to print out any contained symbolic
450 string TypeName = calcTypeName(Ty, TypeNames, MInfo);
451 // TypeNames.insert(std::make_pair(Ty, TypeName));
452 //Cache type name for later use
454 return Out << TypeName << ")" << MInfo;
456 return Out << TypeName;
461 //Internal CWriter class mimics AssemblyWriter.
464 SlotCalculator &Table;
465 const Module *TheModule;
466 map<const Type *, string> TypeNames;
468 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
469 : Out(o), Table(Tab), TheModule(M) {
472 inline void write(const Module *M) { printModule(M); }
474 ostream& printTypeVar(const Type *Ty, const string &VariableName) {
475 return printTypeVarInt(Out, Ty, TypeNames, VariableName);
480 ostream& printType(const Type *Ty, ostream &Out);
481 void writeOperand(const Value *Operand, ostream &Out,bool PrintName = true);
483 string getValueName(const Value *V);
486 void printModule(const Module *M);
487 void printSymbolTable(const SymbolTable &ST);
488 void printConstant(const Constant *CPV);
489 void printGlobal(const GlobalVariable *GV);
490 void printFunctionSignature(const Function *F);
491 void printFunctionDecl(const Function *F); // Print just the forward decl
492 void printFunctionArgument(const Argument *FA);
494 void printFunction(const Function *);
496 void outputBasicBlock(const BasicBlock *);
498 /* END class CWriter */
501 /* CLASS InstLocalVarsVisitor */
502 class InstLocalVarsVisitor : public InstVisitor<InstLocalVarsVisitor> {
504 void handleTerminator(TerminatorInst *tI, int indx);
508 InstLocalVarsVisitor(CWriter &cw) : CW(cw) {}
510 void visitInstruction(Instruction *I) {
511 if (I->getType() != Type::VoidTy) {
512 string tempostr = CW.getValueName(I);
513 CLV.addLocalVar(I->getType(), tempostr);
517 void visitBranchInst(BranchInst *I) {
518 handleTerminator(I, 0);
519 if (I->isConditional())
520 handleTerminator(I, 1);
525 void InstLocalVarsVisitor::handleTerminator(TerminatorInst *tI,int indx) {
526 BasicBlock *bb = tI->getSuccessor(indx);
528 BasicBlock::const_iterator insIt = bb->begin();
529 while (insIt != bb->end()) {
530 if (const PHINode *pI = dyn_cast<PHINode>(*insIt)) {
532 // Calculate the incoming index for this
533 assert(pI->getBasicBlockIndex(tI->getParent()) != -1);
535 CLV.addLocalVar(pI->getType(), CW.getValueName(pI));
543 /* CLASS CInstPrintVisitor */
545 class CInstPrintVisitor: public InstVisitor<CInstPrintVisitor> {
547 SlotCalculator& Table;
549 const Value *Operand;
551 void outputLValue(Instruction *);
552 void printPhiFromNextBlock(TerminatorInst *tI, int indx);
555 CInstPrintVisitor (CWriter &cw, SlotCalculator& table, ostream& o)
556 : CW(cw), Table(table), Out(o) {
560 void visitCastInst(CastInst *I);
561 void visitCallInst(CallInst *I);
562 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
563 void visitReturnInst(ReturnInst *I);
564 void visitBranchInst(BranchInst *I);
565 void visitSwitchInst(SwitchInst *I);
566 void visitInvokeInst(InvokeInst *I) ;
567 void visitMallocInst(MallocInst *I);
568 void visitAllocaInst(AllocaInst *I);
569 void visitFreeInst(FreeInst *I);
570 void visitLoadInst(LoadInst *I);
571 void visitStoreInst(StoreInst *I);
572 void visitGetElementPtrInst(GetElementPtrInst *I);
573 void visitPHINode(PHINode *I) {}
575 void visitNot(GenericUnaryInst *I);
576 void visitBinaryOperator(Instruction *I);
580 void CInstPrintVisitor::outputLValue(Instruction *I) {
581 Out << " " << CW.getValueName(I) << " = ";
584 void CInstPrintVisitor::printPhiFromNextBlock(TerminatorInst *tI, int indx) {
585 BasicBlock *bb = tI->getSuccessor(indx);
586 BasicBlock::const_iterator insIt = bb->begin();
587 while (insIt != bb->end()) {
588 if (PHINode *pI = dyn_cast<PHINode>(*insIt)) {
590 //Calculate the incoming index for this
591 int incindex = pI->getBasicBlockIndex(tI->getParent());
592 if (incindex != -1) {
593 //now we have to do the printing
595 CW.writeOperand(pI->getIncomingValue(incindex), Out);
604 // Implement all "other" instructions, except for PHINode
605 void CInstPrintVisitor::visitCastInst(CastInst *I) {
607 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
609 CW.printType(I->getType(), Out);
611 CW.writeOperand(Operand, Out);
615 void CInstPrintVisitor::visitCallInst(CallInst *I) {
616 if (I->getType() != Type::VoidTy)
621 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
622 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
623 const FunctionType *MTy = PTy
624 ? dyn_cast<FunctionType>(PTy->getElementType()):0;
625 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
627 // If possible, print out the short form of the call instruction, but we can
628 // only do this if the first argument is a pointer to a nonvararg method,
629 // and if the value returned is not a pointer to a method.
631 if (RetTy && !MTy->isVarArg() &&
632 (!isa<PointerType>(RetTy)||
633 !isa<FunctionType>(cast<PointerType>(RetTy)))){
635 Out << makeNameProper(Operand->getName());
637 Out << makeNameProper(Operand->getName());
640 if (I->getNumOperands() > 1)
641 CW.writeOperand(I->getOperand(1), Out);
642 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
644 CW.writeOperand(I->getOperand(op), Out);
650 // Specific Instruction type classes... note that all of the casts are
651 // neccesary because we use the instruction classes as opaque types...
653 void CInstPrintVisitor::visitReturnInst(ReturnInst *I) {
655 if (I->getNumOperands())
656 CW.writeOperand(I->getOperand(0), Out);
660 void CInstPrintVisitor::visitBranchInst(BranchInst *I) {
661 TerminatorInst *tI = cast<TerminatorInst>(I);
662 if (I->isConditional()) {
664 CW.writeOperand(I->getCondition(), Out);
666 printPhiFromNextBlock(tI,0);
668 CW.writeOperand(I->getOperand(0), Out);
670 Out << " } else {\n";
671 printPhiFromNextBlock(tI,1);
673 CW.writeOperand(I->getOperand(1), Out);
676 printPhiFromNextBlock(tI,0);
678 CW.writeOperand(I->getOperand(0), Out);
684 void CInstPrintVisitor::visitSwitchInst(SwitchInst *I) {
685 assert(0 && "Switch not implemented!");
688 void CInstPrintVisitor::visitInvokeInst(InvokeInst *I) {
689 assert(0 && "Invoke not implemented!");
692 void CInstPrintVisitor::visitMallocInst(MallocInst *I) {
695 CW.printType(I->getType()->getElementType(), Out);
696 Out << "*)malloc(sizeof(";
697 CW.printTypeVar(I->getType()->getElementType(), "");
700 if (I->isArrayAllocation()) {
702 CW.writeOperand(I->getOperand(0), Out);
707 void CInstPrintVisitor::visitAllocaInst(AllocaInst *I) {
709 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
712 CW.printTypeVar(I->getType(), tempstr);
713 Out << ") alloca(sizeof(";
714 CW.printTypeVar(cast<PointerType>(I->getType())->getElementType(),
717 if (I->getNumOperands()) {
719 CW.writeOperand(Operand, Out);
724 void CInstPrintVisitor::visitFreeInst(FreeInst *I) {
725 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
727 CW.writeOperand(Operand, Out);
731 void CInstPrintVisitor::visitLoadInst(LoadInst *I) {
733 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
734 if (I->getNumOperands() <= 1) {
736 CW.writeOperand(Operand, Out);
739 //Check if it is an array type or struct type ptr!
741 const PointerType *PTy = dyn_cast<PointerType>(I->getType());
742 if (cast<const PointerType>(Operand->getType())->getElementType()->getPrimitiveID() == Type::StructTyID)
744 if (arrtype && isa<GlobalValue>(Operand))
746 CW.writeOperand(Operand,Out);
747 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
749 if (arrtype || !isa<GlobalValue>(Operand)) {
751 CW.writeOperand(I->getOperand(i), Out);
754 if (isa<GlobalValue>(Operand) && arrtype)
758 if (arrtype == 1) Out << "[";
761 CW.writeOperand(I->getOperand(i), Out);
762 if (arrtype == 1) Out << "]";
769 void CInstPrintVisitor::visitStoreInst(StoreInst *I) {
770 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
771 if (I->getNumOperands() <= 2) {
773 CW.writeOperand(I->getOperand(1), Out);
776 //Check if it is an array type or struct type ptr!
778 if (cast<const PointerType>(I->getOperand(1)->getType())->getElementType()->getPrimitiveID() == Type::StructTyID)
780 if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
782 CW.writeOperand(I->getOperand(1), Out);
783 for (unsigned i = 2, E = I->getNumOperands(); i != E; ++i) {
785 if (arrtype || !isa<GlobalValue>(I->getOperand(1))) {
787 CW.writeOperand(I->getOperand(i), Out);
790 if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
794 if (arrtype == 1) Out << "[";
797 CW.writeOperand(I->getOperand(i), Out);
798 if (arrtype == 1) Out << "]";
803 CW.writeOperand(Operand, Out);
807 void CInstPrintVisitor::visitGetElementPtrInst(GetElementPtrInst *I) {
809 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
811 if (I->getNumOperands() <= 1)
812 CW.writeOperand(Operand, Out);
814 //Check if it is an array type or struct type ptr!
816 if ((cast<const PointerType>(Operand->getType()))->getElementType()->getPrimitiveID() == Type::StructTyID)
818 if ((isa<GlobalValue>(Operand)) && arrtype)
820 CW.writeOperand(Operand, Out);
821 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
823 if (arrtype || !isa<GlobalValue>(Operand)){
825 CW.writeOperand(I->getOperand(i), Out);
828 if (isa<GlobalValue>(Operand) && arrtype)
832 if (arrtype == 1) Out << "[";
835 CW.writeOperand(I->getOperand(i), Out);
836 if (arrtype == 1) Out << "]";
843 void CInstPrintVisitor::visitNot(GenericUnaryInst *I) {
846 CW.writeOperand(I->getOperand(0), Out);
850 void CInstPrintVisitor::visitBinaryOperator(Instruction *I) {
851 // binary instructions, shift instructions, setCond instructions.
853 if (isa<PointerType>(I->getType())) {
855 CW.printType(I->getType(), Out);
859 if (isa<PointerType>(I->getType())) Out << "(long long)";
860 CW.writeOperand(I->getOperand(0), Out);
862 switch (I->getOpcode()) {
863 case Instruction::Add: Out << "+"; break;
864 case Instruction::Sub: Out << "-"; break;
865 case Instruction::Mul: Out << "*"; break;
866 case Instruction::Div: Out << "/"; break;
867 case Instruction::Rem: Out << "%"; break;
868 case Instruction::And: Out << "&"; break;
869 case Instruction::Or: Out << "|"; break;
870 case Instruction::Xor: Out << "^"; break;
871 case Instruction::SetEQ: Out << "=="; break;
872 case Instruction::SetNE: Out << "!="; break;
873 case Instruction::SetLE: Out << "<="; break;
874 case Instruction::SetGE: Out << ">="; break;
875 case Instruction::SetLT: Out << "<"; break;
876 case Instruction::SetGT: Out << ">"; break;
877 case Instruction::Shl : Out << "<<"; break;
878 case Instruction::Shr : Out << ">>"; break;
879 default: cerr << "Invalid operator type!" << I; abort();
882 if (isa<PointerType>(I->getType())) Out << "(long long)";
883 CW.writeOperand(I->getOperand(1), Out);
887 /* END : CInstPrintVisitor implementation */
889 string CWriter::getValueName(const Value *V) {
890 if (V->hasName()) // Print out the label if it exists...
891 return "llvm__" + makeNameProper(V->getName()) + "_" +
892 utostr(V->getType()->getUniqueID());
894 int Slot = Table.getValSlot(V);
895 assert(Slot >= 0 && "Invalid value!");
896 return "llvm__tmp_" + itostr(Slot) + "_" +
897 utostr(V->getType()->getUniqueID());
900 void CWriter::printModule(const Module *M) {
901 // printing stdlib inclusion
902 // Out << "#include <stdlib.h>\n";
904 // get declaration for alloca
905 Out << "/* Provide Declarations */\n"
906 << "#include <alloca.h>\n\n"
908 // Provide a definition for null if one does not already exist.
909 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
910 << "typedef unsigned char bool;\n"
912 << "\n\n/* Global Symbols */\n";
914 // Loop over the symbol table, emitting all named constants...
915 if (M->hasSymbolTable())
916 printSymbolTable(*M->getSymbolTable());
918 Out << "\n\n/* Global Data */\n";
919 for_each(M->gbegin(), M->gend(),
920 bind_obj(this, &CWriter::printGlobal));
922 // First output all the declarations of the functions as C requires Functions
923 // be declared before they are used.
925 Out << "\n\n/* Function Declarations */\n";
926 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
928 // Output all of the functions...
929 Out << "\n\n/* Function Bodies */\n";
930 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
933 // prints the global constants
934 void CWriter::printGlobal(const GlobalVariable *GV) {
935 string tempostr = getValueName(GV);
936 if (GV->hasInternalLinkage()) Out << "static ";
938 printTypeVar(GV->getType()->getElementType(), tempostr);
940 if (GV->hasInitializer()) {
942 writeOperand(GV->getInitializer(), Out, false);
948 // printSymbolTable - Run through symbol table looking for named constants
949 // if a named constant is found, emit it's declaration...
950 // Assuming that symbol table has only types and constants.
951 void CWriter::printSymbolTable(const SymbolTable &ST) {
953 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
954 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
955 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
958 // Need to run through all the used types in the program
959 // FindUsedTypes &FUT = new FindUsedTypes();
960 // const std::set<const Type *> &UsedTypes = FUT.getTypes();
961 // Filter out the structures printing forward definitions for each of them
962 // and creating the dependency graph.
963 // Print forward definitions to all of them
964 // print the typedefs topologically sorted
966 // But for now we have
967 for (; I != End; ++I) {
968 const Value *V = I->second;
969 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
971 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
975 tempostr = "llvm__" + I->first;
976 string TypeNameVar = calcTypeNameVar(Ty, TypeNames,
978 Out << TypeNameVar << ";\n";
979 if (!isa<PointerType>(Ty) ||
980 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
981 TypeNames.insert(std::make_pair(Ty, "llvm__"+I->first));
988 // printConstant - Print out a constant pool entry...
990 void CWriter::printConstant(const Constant *CPV) {
992 // Dinakar : Don't know what to do with unnamed constants
993 // should do something about it later.
995 string tempostr = getValueName(CPV);
997 // Print out the constant type...
998 printTypeVar(CPV->getType(), tempostr);
1001 // Write the value out now...
1002 writeOperand(CPV, Out, false);
1007 // printFunctionDecl - Print function declaration
1009 void CWriter::printFunctionDecl(const Function *F) {
1010 printFunctionSignature(F);
1014 void CWriter::printFunctionSignature(const Function *F) {
1015 if (F->hasInternalLinkage()) Out << "static ";
1017 // Loop over the arguments, printing them...
1018 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1020 // Print out the return type and name...
1021 printType(F->getReturnType(), Out);
1022 Out << " " << makeNameProper(F->getName()) << "(";
1024 if (!F->isExternal()) {
1025 for_each(F->getArgumentList().begin(), F->getArgumentList().end(),
1026 bind_obj(this, &CWriter::printFunctionArgument));
1028 // Loop over the arguments, printing them...
1029 for (FunctionType::ParamTypes::const_iterator I =
1030 FT->getParamTypes().begin(),
1031 E = FT->getParamTypes().end(); I != E; ++I) {
1032 if (I != FT->getParamTypes().begin()) Out << ", ";
1037 // Finish printing arguments...
1038 if (FT->isVarArg()) {
1039 if (FT->getParamTypes().size()) Out << ", ";
1040 Out << "..."; // Output varargs portion of signature!
1046 // printFunctionArgument - This member is called for every argument that
1047 // is passed into the method. Simply print it out
1049 void CWriter::printFunctionArgument(const Argument *Arg) {
1050 // Insert commas as we go... the first arg doesn't get a comma
1051 if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
1054 printTypeVar(Arg->getType(), getValueName(Arg));
1057 void CWriter::printFunction(const Function *F) {
1058 if (F->isExternal()) return;
1060 Table.incorporateFunction(F);
1062 // Process each of the basic blocks, gather information and call the
1063 // output methods on the CLocalVars and Function* objects.
1065 // gather local variable information for each basic block
1066 InstLocalVarsVisitor ILV(*this);
1067 ILV.visit((Function *)F);
1069 printFunctionSignature(F);
1072 // Loop over the symbol table, emitting all named constants...
1073 if (F->hasSymbolTable())
1074 printSymbolTable(*F->getSymbolTable());
1076 // print the local variables
1077 // we assume that every local variable is alloca'ed in the C code.
1078 std::map<const Type*, VarListType> &locals = ILV.CLV.LocalVars;
1080 map<const Type*, VarListType>::iterator iter;
1081 for (iter = locals.begin(); iter != locals.end(); ++iter) {
1082 VarListType::iterator listiter;
1083 for (listiter = iter->second.begin(); listiter != iter->second.end();
1086 printTypeVar(iter->first, *listiter);
1091 // print the basic blocks
1092 for_each(F->begin(), F->end(), bind_obj(this, &CWriter::outputBasicBlock));
1095 Table.purgeFunction();
1098 void CWriter::outputBasicBlock(const BasicBlock* BB) {
1099 Out << getValueName(BB) << ":\n";
1101 // Output all of the instructions in the basic block...
1102 // print the basic blocks
1103 CInstPrintVisitor CIPV(*this, Table, Out);
1104 CIPV.visit((BasicBlock *) BB);
1107 // printType - Go to extreme measures to attempt to print out a short, symbolic
1108 // version of a type name.
1109 ostream& CWriter::printType(const Type *Ty, ostream &Out) {
1110 return printTypeInt(Out, Ty, TypeNames);
1114 void CWriter::writeOperand(const Value *Operand,
1115 ostream &Out, bool PrintName = true) {
1116 if (PrintName && Operand->hasName()) {
1117 // If Operand has a name.
1118 Out << "llvm__" << makeNameProper(Operand->getName()) << "_" <<
1119 Operand->getType()->getUniqueID();
1122 else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
1123 if (isa<ConstantPointerNull>(CPV))
1126 Out << getConstStrValue(CPV);
1129 int Slot = Table.getValSlot(Operand);
1131 Out << "llvm__tmp_" << Slot << "_" << Operand->getType()->getUniqueID();
1138 //===----------------------------------------------------------------------===//
1139 // External Interface declaration
1140 //===----------------------------------------------------------------------===//
1142 void WriteToC(const Module *M, ostream &Out) {
1143 assert(M && "You can't write a null module!!");
1144 SlotCalculator SlotTable(M, false);
1145 CWriter W(Out, SlotTable, M);