blob: dd791872e8e97c2a4f7440341e228e0f0d723994 [file] [log] [blame]
Chris Lattner16c7bb22002-05-09 02:28:59 +00001//===-- Writer.cpp - Library for writing C files --------------------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002//
3// This library implements the functionality defined in llvm/Assembly/CWriter.h
4// and CLocalVars.h
5//
6// TODO : Recursive types.
Chris Lattner16c7bb22002-05-09 02:28:59 +00007//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00008//===-----------------------------------------------------------------------==//
Chris Lattner16c7bb22002-05-09 02:28:59 +00009
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000010#include "llvm/Assembly/CWriter.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000011#include "llvm/SlotCalculator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000012#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000013#include "llvm/DerivedTypes.h"
14#include "llvm/Module.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000015#include "llvm/GlobalVariable.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000016#include "llvm/Function.h"
17#include "llvm/Argument.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000018#include "llvm/BasicBlock.h"
19#include "llvm/iMemory.h"
20#include "llvm/iTerminators.h"
21#include "llvm/iPHINode.h"
22#include "llvm/iOther.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000023#include "llvm/iOperators.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000024#include "llvm/SymbolTable.h"
25#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000026#include "llvm/Support/InstIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000027#include "Support/StringExtras.h"
28#include "Support/STLExtras.h"
29
30#include <algorithm>
31#include <strstream>
32using std::string;
33using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000034using std::ostream;
35
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000036static std::string getConstStrValue(const Constant* CPV);
37
38
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000039static std::string getConstArrayStrValue(const Constant* CPV) {
40 std::string Result;
41
42 // As a special case, print the array as a string if it is an array of
43 // ubytes or an array of sbytes with positive values.
44 //
45 const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
46 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
47
Chris Lattner4fbf26d2002-05-09 20:53:56 +000048 // Make sure the last character is a null char, as automatically added by C
49 if (CPV->getNumOperands() == 0 ||
50 !cast<Constant>(*(CPV->op_end()-1))->isNullValue())
51 isString = false;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000052
53 if (isString) {
54 Result = "\"";
Chris Lattner2f5eb4e2002-05-09 03:56:52 +000055 // Do not include the last character, which we know is null
56 for (unsigned i = 0, e = CPV->getNumOperands()-1; i != e; ++i) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000057 unsigned char C = (ETy == Type::SByteTy) ?
58 (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
59 (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
60
61 if (isprint(C)) {
62 Result += C;
63 } else {
Chris Lattner2f5eb4e2002-05-09 03:56:52 +000064 switch (C) {
65 case '\n': Result += "\\n"; break;
66 case '\t': Result += "\\t"; break;
67 case '\r': Result += "\\r"; break;
68 case '\v': Result += "\\v"; break;
69 case '\a': Result += "\\a"; break;
70 default:
71 Result += "\\x";
72 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
73 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
74 break;
75 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000076 }
77 }
78 Result += "\"";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000079 } else {
80 Result = "{";
81 if (CPV->getNumOperands()) {
82 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
83 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
84 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
85 }
86 Result += " }";
87 }
88
89 return Result;
90}
91
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000092static std::string getConstStrValue(const Constant* CPV) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +000093 switch (CPV->getType()->getPrimitiveID()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +000094 case Type::BoolTyID: return CPV == ConstantBool::False ? "0" : "1";
Chris Lattner3ef6dc72002-05-09 14:40:11 +000095 case Type::SByteTyID:
96 case Type::ShortTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +000097 case Type::IntTyID: return itostr(cast<ConstantSInt>(CPV)->getValue());
98 case Type::LongTyID: return itostr(cast<ConstantSInt>(CPV)->getValue())+"ll";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000099
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000100 case Type::UByteTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000101 case Type::UShortTyID:return utostr(cast<ConstantUInt>(CPV)->getValue());
102 case Type::UIntTyID: return utostr(cast<ConstantUInt>(CPV)->getValue())+"u";
103 case Type::ULongTyID:return utostr(cast<ConstantUInt>(CPV)->getValue())+"ull";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000104
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000105 case Type::FloatTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000106 case Type::DoubleTyID: return ftostr(cast<ConstantFP>(CPV)->getValue());
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000107
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000108 case Type::ArrayTyID: return getConstArrayStrValue(CPV);
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000109
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000110 case Type::StructTyID: {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000111 std::string Result = "{";
112 if (CPV->getNumOperands()) {
113 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
114 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
115 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000116 }
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000117 return Result + " }";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000118 }
119
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000120 default:
121 cerr << "Unknown constant type: " << CPV << "\n";
122 abort();
123 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000124}
125
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000126// Pass the Type* variable and and the variable name and this prints out the
127// variable declaration.
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000128//
Chris Lattner16c7bb22002-05-09 02:28:59 +0000129static string calcTypeNameVar(const Type *Ty,
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000130 map<const Type *, string> &TypeNames,
131 const string &NameSoFar, bool ignoreName = false){
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000132 if (Ty->isPrimitiveType())
133 switch (Ty->getPrimitiveID()) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000134 case Type::VoidTyID: return "void " + NameSoFar;
135 case Type::BoolTyID: return "bool " + NameSoFar;
136 case Type::UByteTyID: return "unsigned char " + NameSoFar;
137 case Type::SByteTyID: return "signed char " + NameSoFar;
138 case Type::UShortTyID: return "unsigned short " + NameSoFar;
139 case Type::ShortTyID: return "short " + NameSoFar;
140 case Type::UIntTyID: return "unsigned " + NameSoFar;
141 case Type::IntTyID: return "int " + NameSoFar;
142 case Type::ULongTyID: return "unsigned long long " + NameSoFar;
143 case Type::LongTyID: return "signed long long " + NameSoFar;
Chris Lattner1f02c892002-05-09 20:14:10 +0000144 case Type::FloatTyID: return "float " + NameSoFar;
145 case Type::DoubleTyID: return "double " + NameSoFar;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000146 default :
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000147 cerr << "Unknown primitive type: " << Ty << "\n";
148 abort();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000149 }
150
151 // Check to see if the type is named.
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000152 if (!ignoreName) {
153 map<const Type *, string>::iterator I = TypeNames.find(Ty);
154 if (I != TypeNames.end())
155 return I->second + " " + NameSoFar;
156 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000157
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000158 string Result;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000159 switch (Ty->getPrimitiveID()) {
160 case Type::FunctionTyID: {
Chris Lattner7683a122002-05-09 20:33:35 +0000161 const FunctionType *MTy = cast<FunctionType>(Ty);
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000162 Result += calcTypeNameVar(MTy->getReturnType(), TypeNames, "");
Chris Lattner7683a122002-05-09 20:33:35 +0000163 Result += " " + NameSoFar + " (";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000164 for (FunctionType::ParamTypes::const_iterator
165 I = MTy->getParamTypes().begin(),
166 E = MTy->getParamTypes().end(); I != E; ++I) {
167 if (I != MTy->getParamTypes().begin())
168 Result += ", ";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000169 Result += calcTypeNameVar(*I, TypeNames, "");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000170 }
171 if (MTy->isVarArg()) {
172 if (!MTy->getParamTypes().empty())
173 Result += ", ";
174 Result += "...";
175 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000176 return Result + ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000177 }
178 case Type::StructTyID: {
179 const StructType *STy = cast<const StructType>(Ty);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000180 Result = NameSoFar + " {\n";
181 unsigned indx = 0;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000182 for (StructType::ElementTypes::const_iterator
183 I = STy->getElementTypes().begin(),
184 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000185 Result += " " +calcTypeNameVar(*I, TypeNames, "field" + utostr(indx++));
186 Result += ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000187 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000188 return Result + "}";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000189 }
190
191 case Type::PointerTyID: {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000192 return calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(),
193 TypeNames, "*" + NameSoFar);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000194 }
195
196 case Type::ArrayTyID: {
197 const ArrayType *ATy = cast<const ArrayType>(Ty);
198 int NumElements = ATy->getNumElements();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000199 return calcTypeNameVar(ATy->getElementType(), TypeNames,
200 NameSoFar + "[" + itostr(NumElements) + "]");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000201 }
202 default:
203 assert(0 && "Unhandled case in getTypeProps!");
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000204 abort();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000205 }
206
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000207 return Result;
208}
209
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000210namespace {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000211 class CWriter : public InstVisitor<CWriter> {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000212 ostream& Out;
213 SlotCalculator &Table;
214 const Module *TheModule;
215 map<const Type *, string> TypeNames;
216 public:
217 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
218 : Out(o), Table(Tab), TheModule(M) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000219 }
220
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000221 inline void write(Module *M) { printModule(M); }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000222
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000223 ostream& printTypeVar(const Type *Ty, const string &VariableName) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000224 return Out << calcTypeNameVar(Ty, TypeNames, VariableName);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000225 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000226
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000227 ostream& printType(const Type *Ty) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000228 return Out << calcTypeNameVar(Ty, TypeNames, "");
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000229 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000230
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000231 void writeOperand(const Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000232
233 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000234
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000235 private :
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000236 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000237 void printSymbolTable(const SymbolTable &ST);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000238 void printGlobal(const GlobalVariable *GV);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000239 void printFunctionSignature(const Function *F);
240 void printFunctionDecl(const Function *F); // Print just the forward decl
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000241
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000242 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000243
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000244 // Instruction visitation functions
245 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000246
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000247 void visitReturnInst(ReturnInst *I);
248 void visitBranchInst(BranchInst *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000249
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000250 void visitPHINode(PHINode *I) {}
251 void visitNot(GenericUnaryInst *I);
252 void visitBinaryOperator(Instruction *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000253
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000254 void visitCastInst(CastInst *I);
255 void visitCallInst(CallInst *I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000256 void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000257
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000258 void visitMallocInst(MallocInst *I);
259 void visitAllocaInst(AllocaInst *I);
260 void visitFreeInst(FreeInst *I);
261 void visitLoadInst(LoadInst *I);
262 void visitStoreInst(StoreInst *I);
263 void visitGetElementPtrInst(GetElementPtrInst *I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000264
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000265 void visitInstruction(Instruction *I) {
266 cerr << "C Writer does not know about " << I;
267 abort();
268 }
269
270 void outputLValue(Instruction *I) {
271 Out << " " << getValueName(I) << " = ";
272 }
273 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
274 unsigned Indent);
275 void printIndexingExpr(MemAccessInst *MAI);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000276 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000277}
278
Chris Lattner2f499022002-05-09 04:21:21 +0000279// We dont want identifier names with ., space, - in them.
280// So we replace them with _
281static string makeNameProper(string x) {
282 string tmp;
283 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
284 switch (*sI) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000285 case '.': tmp += "d_"; break;
286 case ' ': tmp += "s_"; break;
287 case '-': tmp += "D_"; break;
Chris Lattner2f499022002-05-09 04:21:21 +0000288 case '_': tmp += "__"; break;
289 default: tmp += *sI;
290 }
291
292 return tmp;
293}
294
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000295string CWriter::getValueName(const Value *V) {
Chris Lattner2f499022002-05-09 04:21:21 +0000296 if (V->hasName()) { // Print out the label if it exists...
297 if (isa<GlobalValue>(V)) // Do not mangle globals...
298 return makeNameProper(V->getName());
299
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000300 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
301 makeNameProper(V->getName());
Chris Lattner2f499022002-05-09 04:21:21 +0000302 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000303
304 int Slot = Table.getValSlot(V);
305 assert(Slot >= 0 && "Invalid value!");
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000306 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000307}
308
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000309void CWriter::writeOperand(const Value *Operand) {
310 if (isa<GlobalVariable>(Operand))
311 Out << "(&"; // Global variables are references as their addresses by llvm
312
313 if (Operand->hasName()) {
314 Out << getValueName(Operand);
315 } else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
316 if (isa<ConstantPointerNull>(CPV)) {
317 Out << "((";
318 printTypeVar(CPV->getType(), "");
319 Out << ")NULL)";
320 } else
321 Out << getConstStrValue(CPV);
322 } else {
323 int Slot = Table.getValSlot(Operand);
324 assert(Slot >= 0 && "Malformed LLVM!");
325 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
326 }
327
328 if (isa<GlobalVariable>(Operand))
329 Out << ")";
330}
331
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000332void CWriter::printModule(Module *M) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000333 // printing stdlib inclusion
334 // Out << "#include <stdlib.h>\n";
335
Chris Lattner16c7bb22002-05-09 02:28:59 +0000336 // get declaration for alloca
337 Out << "/* Provide Declarations */\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000338 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000339
340 // Provide a definition for null if one does not already exist.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000341 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000342 << "typedef unsigned char bool;\n"
343
344 << "\n\n/* Global Symbols */\n";
345
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000346 // Loop over the symbol table, emitting all named constants...
347 if (M->hasSymbolTable())
348 printSymbolTable(*M->getSymbolTable());
349
Chris Lattner16c7bb22002-05-09 02:28:59 +0000350 Out << "\n\n/* Global Data */\n";
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000351 for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
352 GlobalVariable *GV = *I;
353 if (GV->hasInternalLinkage()) Out << "static ";
354 printTypeVar(GV->getType()->getElementType(), getValueName(GV));
355
356 if (GV->hasInitializer()) {
357 Out << " = " ;
358 writeOperand(GV->getInitializer());
359 }
360 Out << ";\n";
361 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000362
Chris Lattner16c7bb22002-05-09 02:28:59 +0000363 // First output all the declarations of the functions as C requires Functions
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000364 // be declared before they are used.
Chris Lattner16c7bb22002-05-09 02:28:59 +0000365 //
366 Out << "\n\n/* Function Declarations */\n";
367 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000368
Chris Lattner16c7bb22002-05-09 02:28:59 +0000369 // Output all of the functions...
370 Out << "\n\n/* Function Bodies */\n";
371 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000372}
373
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000374
375// printSymbolTable - Run through symbol table looking for named constants
376// if a named constant is found, emit it's declaration...
377// Assuming that symbol table has only types and constants.
378void CWriter::printSymbolTable(const SymbolTable &ST) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000379 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
380 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
381 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
382
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000383 for (; I != End; ++I)
384 if (const Type *Ty = dyn_cast<const StructType>(I->second)) {
385 string Name = "struct l_" + I->first;
386 Out << Name << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000387
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000388 TypeNames.insert(std::make_pair(Ty, Name));
389 }
390 }
391
392 Out << "\n";
393
394 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
395 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
396 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
397
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000398 for (; I != End; ++I) {
399 const Value *V = I->second;
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000400 if (const Type *Ty = dyn_cast<const Type>(V)) {
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000401 string Name = "l_" + I->first;
Chris Lattner1f02c892002-05-09 20:14:10 +0000402 if (isa<StructType>(Ty))
403 Name = "struct " + Name;
404 else
405 Out << "typedef ";
406
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000407 Out << calcTypeNameVar(Ty, TypeNames, Name, true) << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000408 }
409 }
410 }
411}
412
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000413
Chris Lattner16c7bb22002-05-09 02:28:59 +0000414// printFunctionDecl - Print function declaration
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000415//
Chris Lattner16c7bb22002-05-09 02:28:59 +0000416void CWriter::printFunctionDecl(const Function *F) {
417 printFunctionSignature(F);
418 Out << ";\n";
419}
420
421void CWriter::printFunctionSignature(const Function *F) {
422 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000423
424 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000425 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000426
Chris Lattner16c7bb22002-05-09 02:28:59 +0000427 // Print out the return type and name...
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000428 printType(F->getReturnType());
Chris Lattner1f02c892002-05-09 20:14:10 +0000429 Out << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000430
Chris Lattner16c7bb22002-05-09 02:28:59 +0000431 if (!F->isExternal()) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000432 if (!F->getArgumentList().empty()) {
433 printTypeVar(F->getArgumentList().front()->getType(),
434 getValueName(F->getArgumentList().front()));
435
436 for (Function::ArgumentListType::const_iterator
437 I = F->getArgumentList().begin()+1,
438 E = F->getArgumentList().end(); I != E; ++I) {
439 Out << ", ";
440 printTypeVar((*I)->getType(), getValueName(*I));
441 }
442 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000443 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000444 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000445 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000446 FT->getParamTypes().begin(),
447 E = FT->getParamTypes().end(); I != E; ++I) {
448 if (I != FT->getParamTypes().begin()) Out << ", ";
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000449 printType(*I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000450 }
451 }
452
453 // Finish printing arguments...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000454 if (FT->isVarArg()) {
455 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000456 Out << "..."; // Output varargs portion of signature!
457 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000458 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000459}
460
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000461
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000462void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000463 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000464
Chris Lattnerf34ee812002-05-09 03:12:34 +0000465 Table.incorporateFunction(F);
466
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000467 printFunctionSignature(F);
468 Out << " {\n";
469
Chris Lattner497e19a2002-05-09 20:39:03 +0000470 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000471 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner497e19a2002-05-09 20:39:03 +0000472 if ((*I)->getType() != Type::VoidTy) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000473 Out << " ";
Chris Lattner497e19a2002-05-09 20:39:03 +0000474 printTypeVar((*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000475 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000476 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000477
478 // print the basic blocks
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000479 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
480 BasicBlock *BB = *I, *Prev = I != F->begin() ? *(I-1) : 0;
481
482 // Don't print the label for the basic block if there are no uses, or if the
483 // only terminator use is the precessor basic block's terminator. We have
484 // to scan the use list because PHI nodes use basic blocks too but do not
485 // require a label to be generated.
486 //
487 bool NeedsLabel = false;
488 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
489 UI != UE; ++UI)
490 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
491 if (TI != Prev->getTerminator()) {
492 NeedsLabel = true;
493 break;
494 }
495
496 if (NeedsLabel) Out << getValueName(BB) << ":\n";
497
498 // Output all of the instructions in the basic block...
499 // print the basic blocks
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000500 visit(BB);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000501 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000502
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000503 Out << "}\n\n";
Chris Lattnerf34ee812002-05-09 03:12:34 +0000504 Table.purgeFunction();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000505}
506
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000507// Specific Instruction type classes... note that all of the casts are
508// neccesary because we use the instruction classes as opaque types...
509//
510void CWriter::visitReturnInst(ReturnInst *I) {
511 // Don't output a void return if this is the last basic block in the function
512 if (I->getNumOperands() == 0 &&
513 *(I->getParent()->getParent()->end()-1) == I->getParent())
514 return;
Chris Lattner44408262002-05-09 03:50:42 +0000515
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000516 Out << " return";
517 if (I->getNumOperands()) {
518 Out << " ";
519 writeOperand(I->getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000520 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000521 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000522}
523
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000524// Return true if BB1 immediately preceeds BB2.
525static bool BBFollowsBB(BasicBlock *BB1, BasicBlock *BB2) {
526 Function *F = BB1->getParent();
527 Function::iterator I = find(F->begin(), F->end(), BB1);
528 assert(I != F->end() && "BB not in function!");
529 return *(I+1) == BB2;
530}
531
532static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
533 // If PHI nodes need copies, we need the copy code...
534 if (isa<PHINode>(To->front()) ||
535 !BBFollowsBB(From, To)) // Not directly successor, need goto
536 return true;
537
538 // Otherwise we don't need the code.
539 return false;
540}
541
542void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
543 unsigned Indent) {
544 for (BasicBlock::iterator I = Succ->begin();
545 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
546 // now we have to do the printing
547 Out << string(Indent, ' ');
548 outputLValue(PN);
549 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
550 Out << "; /* for PHI node */\n";
551 }
552
553 if (!BBFollowsBB(CurBB, Succ)) {
554 Out << string(Indent, ' ') << " goto ";
555 writeOperand(Succ);
556 Out << ";\n";
557 }
558}
559
560// Brach instruction printing - Avoid printing out a brach to a basic block that
561// immediately succeeds the current one.
562//
563void CWriter::visitBranchInst(BranchInst *I) {
564 if (I->isConditional()) {
565 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(0))) {
566 Out << " if (";
567 writeOperand(I->getCondition());
568 Out << ") {\n";
569
570 printBranchToBlock(I->getParent(), I->getSuccessor(0), 2);
571
572 if (isGotoCodeNeccessary(I->getParent(), I->getSuccessor(1))) {
573 Out << " } else {\n";
574 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
575 }
576 } else {
577 // First goto not neccesary, assume second one is...
578 Out << " if (!";
579 writeOperand(I->getCondition());
580 Out << ") {\n";
581
582 printBranchToBlock(I->getParent(), I->getSuccessor(1), 2);
583 }
584
585 Out << " }\n";
586 } else {
587 printBranchToBlock(I->getParent(), I->getSuccessor(0), 0);
588 }
589 Out << "\n";
590}
591
592
593void CWriter::visitNot(GenericUnaryInst *I) {
594 outputLValue(I);
595 Out << "~";
596 writeOperand(I->getOperand(0));
597 Out << ";\n";
598}
599
600void CWriter::visitBinaryOperator(Instruction *I) {
601 // binary instructions, shift instructions, setCond instructions.
602 outputLValue(I);
603 if (isa<PointerType>(I->getType())) {
604 Out << "(";
605 printType(I->getType());
606 Out << ")";
607 }
608
609 if (isa<PointerType>(I->getType())) Out << "(long long)";
610 writeOperand(I->getOperand(0));
611
612 switch (I->getOpcode()) {
613 case Instruction::Add: Out << " + "; break;
614 case Instruction::Sub: Out << " - "; break;
615 case Instruction::Mul: Out << "*"; break;
616 case Instruction::Div: Out << "/"; break;
617 case Instruction::Rem: Out << "%"; break;
618 case Instruction::And: Out << " & "; break;
619 case Instruction::Or: Out << " | "; break;
620 case Instruction::Xor: Out << " ^ "; break;
621 case Instruction::SetEQ: Out << " == "; break;
622 case Instruction::SetNE: Out << " != "; break;
623 case Instruction::SetLE: Out << " <= "; break;
624 case Instruction::SetGE: Out << " >= "; break;
625 case Instruction::SetLT: Out << " < "; break;
626 case Instruction::SetGT: Out << " > "; break;
627 case Instruction::Shl : Out << " << "; break;
628 case Instruction::Shr : Out << " >> "; break;
629 default: cerr << "Invalid operator type!" << I; abort();
630 }
631
632 if (isa<PointerType>(I->getType())) Out << "(long long)";
633 writeOperand(I->getOperand(1));
634 Out << ";\n";
635}
636
637void CWriter::visitCastInst(CastInst *I) {
638 outputLValue(I);
639 Out << "(";
640 printType(I->getType());
641 Out << ")";
642 writeOperand(I->getOperand(0));
643 Out << ";\n";
644}
645
646void CWriter::visitCallInst(CallInst *I) {
647 if (I->getType() != Type::VoidTy)
648 outputLValue(I);
649 else
650 Out << " ";
651
652 const PointerType *PTy = cast<PointerType>(I->getCalledValue()->getType());
653 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
654 const Type *RetTy = FTy->getReturnType();
655
656 Out << getValueName(I->getOperand(0)) << "(";
657
658 if (I->getNumOperands() > 1) {
659 writeOperand(I->getOperand(1));
660
661 for (unsigned op = 2, Eop = I->getNumOperands(); op != Eop; ++op) {
662 Out << ", ";
663 writeOperand(I->getOperand(op));
664 }
665 }
666 Out << ");\n";
667}
668
669void CWriter::visitMallocInst(MallocInst *I) {
670 outputLValue(I);
671 Out << "(";
672 printType(I->getType());
673 Out << ")malloc(sizeof(";
674 printType(I->getType()->getElementType());
675 Out << ")";
676
677 if (I->isArrayAllocation()) {
678 Out << " * " ;
679 writeOperand(I->getOperand(0));
680 }
681 Out << ");\n";
682}
683
684void CWriter::visitAllocaInst(AllocaInst *I) {
685 outputLValue(I);
686 Out << "(";
687 printType(I->getType());
688 Out << ") alloca(sizeof(";
689 printType(I->getType()->getElementType());
690 Out << ")";
691 if (I->isArrayAllocation()) {
692 Out << " * " ;
693 writeOperand(I->getOperand(0));
694 }
695 Out << ");\n";
696}
697
698void CWriter::visitFreeInst(FreeInst *I) {
699 Out << " free(";
700 writeOperand(I->getOperand(0));
701 Out << ");\n";
702}
703
704void CWriter::printIndexingExpr(MemAccessInst *MAI) {
705 MemAccessInst::op_iterator I = MAI->idx_begin(), E = MAI->idx_end();
706 if (I == E)
707 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
708
709 writeOperand(MAI->getPointerOperand());
710
711 if (I == E) return;
712
713 // Print out the -> operator if possible...
714 Constant *CI = dyn_cast<Constant>(*I);
715 if (CI && CI->isNullValue() && I+1 != E &&
716 (*(I+1))->getType() == Type::UByteTy) {
717 ++I;
718 Out << "->field" << cast<ConstantUInt>(*I)->getValue();
719 ++I;
720 }
721
722 for (; I != E; ++I)
723 if ((*I)->getType() == Type::UIntTy) {
724 Out << "[";
725 writeOperand(*I);
726 Out << "]";
727 } else {
728 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
729 }
730}
731
732void CWriter::visitLoadInst(LoadInst *I) {
733 outputLValue(I);
734 printIndexingExpr(I);
735 Out << ";\n";
736}
737
738void CWriter::visitStoreInst(StoreInst *I) {
739 Out << " ";
740 printIndexingExpr(I);
741 Out << " = ";
742 writeOperand(I->getOperand(0));
743 Out << ";\n";
744}
745
746void CWriter::visitGetElementPtrInst(GetElementPtrInst *I) {
747 outputLValue(I);
748 Out << "&";
749 printIndexingExpr(I);
750 Out << ";\n";
751}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000752
753//===----------------------------------------------------------------------===//
754// External Interface declaration
755//===----------------------------------------------------------------------===//
756
Chris Lattnerf34ee812002-05-09 03:12:34 +0000757void WriteToC(const Module *M, ostream &Out) {
758 assert(M && "You can't write a null module!!");
759 SlotCalculator SlotTable(M, false);
760 CWriter W(Out, SlotTable, M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000761 W.write((Module*)M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000762 Out.flush();
763}