blob: 1794ff285f180ab7f0b8b71e64a2adb6ac9b15ca [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"
11#include "CLocalVars.h"
12#include "llvm/SlotCalculator.h"
13#include "llvm/Module.h"
14#include "llvm/Argument.h"
15#include "llvm/Function.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Constants.h"
18#include "llvm/GlobalVariable.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/SymbolTable.h"
25#include "llvm/Support/InstVisitor.h"
26#include "Support/StringExtras.h"
27#include "Support/STLExtras.h"
28
29#include <algorithm>
30#include <strstream>
31using std::string;
32using std::map;
33using std::vector;
34using std::ostream;
35
Chris Lattner16c7bb22002-05-09 02:28:59 +000036//===-----------------------------------------------------------------------==//
37//
38// Implementation of the CLocalVars methods
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000039
40// Appends a variable to the LocalVars map if it does not already exist
41// Also check that the type exists on the map.
42void CLocalVars::addLocalVar(const Type *t, const string & var) {
43 if (!LocalVars.count(t) ||
44 find(LocalVars[t].begin(), LocalVars[t].end(), var)
45 == LocalVars[t].end()) {
46 LocalVars[t].push_back(var);
47 }
48}
49
Chris Lattner16c7bb22002-05-09 02:28:59 +000050static string calcTypeNameVar(const Type *Ty,
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000051 map<const Type *, string> &TypeNames,
52 string VariableName, string NameSoFar);
53
54static std::string getConstStrValue(const Constant* CPV);
55
56
57//
58//Getting opcodes in terms of the operator
59//
60static const char *getOpcodeOperName(const Instruction *I) {
61 switch (I->getOpcode()) {
62 // Standard binary operators...
63 case Instruction::Add: return "+";
64 case Instruction::Sub: return "-";
65 case Instruction::Mul: return "*";
66 case Instruction::Div: return "/";
67 case Instruction::Rem: return "%";
68
69 // Logical operators...
70 case Instruction::And: return "&";
71 case Instruction::Or: return "|";
72 case Instruction::Xor: return "^";
73
74 // SetCond operators...
75 case Instruction::SetEQ: return "==";
76 case Instruction::SetNE: return "!=";
77 case Instruction::SetLE: return "<=";
78 case Instruction::SetGE: return ">=";
79 case Instruction::SetLT: return "<";
80 case Instruction::SetGT: return ">";
81
82 //ShiftInstruction...
83
84 case Instruction::Shl : return "<<";
85 case Instruction::Shr : return ">>";
86
87 default:
88 cerr << "Invalid operator type!" << I->getOpcode() << "\n";
89 abort();
90 }
91 return 0;
92}
93
94
95// We dont want identifier names with ., space, - in them.
96// So we replace them with _
97static string makeNameProper(string x) {
98 string tmp;
99 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++) {
100 if (*sI == '.')
101 tmp += '_';
102 else if (*sI == ' ')
103 tmp += '_';
104 else if (*sI == '-')
105 tmp += "__";
106 else
107 tmp += *sI;
108 }
109 return tmp;
110}
111
112static string getConstantName(const Constant *CPV) {
113 return CPV->getName();
114}
115
116
117static std::string getConstArrayStrValue(const Constant* CPV) {
118 std::string Result;
119
120 // As a special case, print the array as a string if it is an array of
121 // ubytes or an array of sbytes with positive values.
122 //
123 const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
124 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
125
126 if (ETy == Type::SByteTy) {
127 for (unsigned i = 0; i < CPV->getNumOperands(); ++i)
128 if (ETy == Type::SByteTy &&
129 cast<ConstantSInt>(CPV->getOperand(i))->getValue() < 0) {
130 isString = false;
131 break;
132 }
133 }
134
135 if (isString) {
136 Result = "\"";
137 for (unsigned i = 0; i < CPV->getNumOperands(); ++i) {
138 unsigned char C = (ETy == Type::SByteTy) ?
139 (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
140 (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
141
142 if (isprint(C)) {
143 Result += C;
144 } else {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000145 Result += "\\x";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000146 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
147 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
148 }
149 }
150 Result += "\"";
151
152 } else {
153 Result = "{";
154 if (CPV->getNumOperands()) {
155 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
156 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
157 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
158 }
159 Result += " }";
160 }
161
162 return Result;
163}
164
165static std::string getConstStructStrValue(const Constant* CPV) {
166 std::string Result = "{";
167 if (CPV->getNumOperands()) {
168 Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
169 for (unsigned i = 1; i < CPV->getNumOperands(); i++)
170 Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
171 }
172
173 return Result + " }";
174}
175
176// our own getStrValue function for constant initializers
177static std::string getConstStrValue(const Constant* CPV) {
178 // Does not handle null pointers, that needs to be checked explicitly
179 string tempstr;
180 if (CPV == ConstantBool::False)
181 return "0";
182 else if (CPV == ConstantBool::True)
183 return "1";
184
185 else if (isa<ConstantArray>(CPV)) {
186 tempstr = getConstArrayStrValue(CPV);
187 }
188 else if (isa<ConstantStruct>(CPV)) {
189 tempstr = getConstStructStrValue(CPV);
190 }
191 else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CPV)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000192 tempstr = utostr(CUI->getValue());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000193 }
194 else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CPV)) {
195 tempstr = itostr(CSI->getValue());
196 }
197 else if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
198 tempstr = ftostr(CFP->getValue());
199 }
200
201 if (CPV->getType() == Type::ULongTy)
202 tempstr += "ull";
203 else if (CPV->getType() == Type::LongTy)
204 tempstr += "ll";
205 else if (CPV->getType() == Type::UIntTy ||
206 CPV->getType() == Type::UShortTy)
207 tempstr += "u";
208
209 return tempstr;
210
211}
212
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000213// Internal function
214// Essentially pass the Type* variable, an empty typestack and this prints
215// out the C type
Chris Lattner16c7bb22002-05-09 02:28:59 +0000216static string calcTypeName(const Type *Ty, map<const Type *, string> &TypeNames,
217 string &FunctionInfo) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000218
219 // Takin' care of the fact that boolean would be int in C
220 // and that ushort would be unsigned short etc.
221
222 // Base Case
223 if (Ty->isPrimitiveType())
224 switch (Ty->getPrimitiveID()) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000225 case Type::VoidTyID: return "void";
226 case Type::BoolTyID: return "bool";
227 case Type::UByteTyID: return "unsigned char";
228 case Type::SByteTyID: return "signed char";
229 case Type::UShortTyID: return "unsigned short";
230 case Type::ShortTyID: return "short";
231 case Type::UIntTyID: return "unsigned";
232 case Type::IntTyID: return "int";
233 case Type::ULongTyID: return "unsigned long long";
234 case Type::LongTyID: return "signed long long";
235 case Type::FloatTyID: return "float";
236 case Type::DoubleTyID: return "double";
237 default : assert(0 && "Unknown primitive type!");
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000238 }
239
240 // Check to see if the type is named.
241 map<const Type *, string>::iterator I = TypeNames.find(Ty);
242 if (I != TypeNames.end())
243 return I->second;
244
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000245 string Result;
246 string MInfo = "";
247 switch (Ty->getPrimitiveID()) {
248 case Type::FunctionTyID: {
249 const FunctionType *MTy = cast<const FunctionType>(Ty);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000250 Result = calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000251 if (MInfo != "")
252 Result += ") " + MInfo;
253 Result += "(";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000254 FunctionInfo += " (";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000255 for (FunctionType::ParamTypes::const_iterator
256 I = MTy->getParamTypes().begin(),
257 E = MTy->getParamTypes().end(); I != E; ++I) {
258 if (I != MTy->getParamTypes().begin())
Chris Lattner16c7bb22002-05-09 02:28:59 +0000259 FunctionInfo += ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000260 MInfo = "";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000261 FunctionInfo += calcTypeName(*I, TypeNames, MInfo);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000262 if (MInfo != "")
263 Result += ") " + MInfo;
264 }
265 if (MTy->isVarArg()) {
266 if (!MTy->getParamTypes().empty())
Chris Lattner16c7bb22002-05-09 02:28:59 +0000267 FunctionInfo += ", ";
268 FunctionInfo += "...";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000269 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000270 FunctionInfo += ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000271 break;
272 }
273 case Type::StructTyID: {
274 string tempstr = "";
275 const StructType *STy = cast<const StructType>(Ty);
276 Result = " struct {\n ";
277 int indx = 0;
278 for (StructType::ElementTypes::const_iterator
279 I = STy->getElementTypes().begin(),
280 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000281 Result += calcTypeNameVar(*I, TypeNames,
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000282 "field" + itostr(indx++), tempstr);
283 Result += ";\n ";
284 }
285 Result += " } ";
286 break;
287 }
288 case Type::PointerTyID:
289 Result = calcTypeName(cast<const PointerType>(Ty)->getElementType(),
Chris Lattner16c7bb22002-05-09 02:28:59 +0000290 TypeNames, MInfo);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000291 Result += "*";
292 break;
293 case Type::ArrayTyID: {
294 const ArrayType *ATy = cast<const ArrayType>(Ty);
295 int NumElements = ATy->getNumElements();
Chris Lattner16c7bb22002-05-09 02:28:59 +0000296 Result = calcTypeName(ATy->getElementType(), TypeNames, MInfo);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000297 Result += "*";
298 break;
299 }
300 default:
301 assert(0 && "Unhandled case in getTypeProps!");
302 Result = "<error>";
303 }
304
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000305 return Result;
306}
307
308// Internal function
309// Pass the Type* variable and and the variable name and this prints out the
310// variable declaration.
311// This is different from calcTypeName because if you need to declare an array
312// the size of the array would appear after the variable name itself
313// For eg. int a[10];
Chris Lattner16c7bb22002-05-09 02:28:59 +0000314static string calcTypeNameVar(const Type *Ty,
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000315 map<const Type *, string> &TypeNames,
316 string VariableName, string NameSoFar) {
317 if (Ty->isPrimitiveType())
318 switch (Ty->getPrimitiveID()) {
319 case Type::BoolTyID:
Chris Lattner16c7bb22002-05-09 02:28:59 +0000320 return "bool " + NameSoFar + VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000321 case Type::UByteTyID:
322 return "unsigned char " + NameSoFar + VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000323 case Type::SByteTyID:
324 return "signed char " + NameSoFar + VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000325 case Type::UShortTyID:
326 return "unsigned long long " + NameSoFar + VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000327 case Type::ULongTyID:
328 return "unsigned long long " + NameSoFar + VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000329 case Type::LongTyID:
330 return "signed long long " + NameSoFar + VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000331 case Type::UIntTyID:
Chris Lattner16c7bb22002-05-09 02:28:59 +0000332 return "unsigned " + NameSoFar + VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000333 default :
334 return Ty->getDescription() + " " + NameSoFar + VariableName;
335 }
336
337 // Check to see if the type is named.
338 map<const Type *, string>::iterator I = TypeNames.find(Ty);
339 if (I != TypeNames.end())
340 return I->second + " " + NameSoFar + VariableName;
341
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000342 string Result;
343 string tempstr = "";
344
345 switch (Ty->getPrimitiveID()) {
346 case Type::FunctionTyID: {
347 string MInfo = "";
348 const FunctionType *MTy = cast<const FunctionType>(Ty);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000349 Result += calcTypeName(MTy->getReturnType(), TypeNames, MInfo);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000350 if (MInfo != "")
351 Result += ") " + MInfo;
352 Result += " " + NameSoFar + VariableName;
353 Result += " (";
354 for (FunctionType::ParamTypes::const_iterator
355 I = MTy->getParamTypes().begin(),
356 E = MTy->getParamTypes().end(); I != E; ++I) {
357 if (I != MTy->getParamTypes().begin())
358 Result += ", ";
359 MInfo = "";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000360 Result += calcTypeName(*I, TypeNames, MInfo);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000361 if (MInfo != "")
362 Result += ") " + MInfo;
363 }
364 if (MTy->isVarArg()) {
365 if (!MTy->getParamTypes().empty())
366 Result += ", ";
367 Result += "...";
368 }
369 Result += ")";
370 break;
371 }
372 case Type::StructTyID: {
373 const StructType *STy = cast<const StructType>(Ty);
374 Result = " struct {\n ";
375 int indx = 0;
376 for (StructType::ElementTypes::const_iterator
377 I = STy->getElementTypes().begin(),
378 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000379 Result += calcTypeNameVar(*I, TypeNames,
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000380 "field" + itostr(indx++), "");
381 Result += ";\n ";
382 }
383 Result += " }";
384 Result += " " + NameSoFar + VariableName;
385 break;
386 }
387
388 case Type::PointerTyID: {
389 Result = calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(),
Chris Lattner16c7bb22002-05-09 02:28:59 +0000390 TypeNames, tempstr,
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000391 "(*" + NameSoFar + VariableName + ")");
392 break;
393 }
394
395 case Type::ArrayTyID: {
396 const ArrayType *ATy = cast<const ArrayType>(Ty);
397 int NumElements = ATy->getNumElements();
Chris Lattner16c7bb22002-05-09 02:28:59 +0000398 Result = calcTypeNameVar(ATy->getElementType(), TypeNames,
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000399 tempstr, NameSoFar + VariableName + "[" +
400 itostr(NumElements) + "]");
401 break;
402 }
403 default:
404 assert(0 && "Unhandled case in getTypeProps!");
405 Result = "<error>";
406 }
407
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000408 return Result;
409}
410
411// printTypeVarInt - The internal guts of printing out a type that has a
412// potentially named portion and the variable associated with the type.
413static ostream &printTypeVarInt(ostream &Out, const Type *Ty,
414 map<const Type *, string> &TypeNames,
415 string VariableName) {
416 // Primitive types always print out their description, regardless of whether
417 // they have been named or not.
418
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000419 if (Ty->isPrimitiveType())
420 switch (Ty->getPrimitiveID()) {
421 case Type::BoolTyID:
Chris Lattner16c7bb22002-05-09 02:28:59 +0000422 return Out << "bool " << VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000423 case Type::UByteTyID:
424 return Out << "unsigned char " << VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000425 case Type::SByteTyID:
426 return Out << "signed char " << VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000427 case Type::UShortTyID:
428 return Out << "unsigned long long " << VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000429 case Type::ULongTyID:
430 return Out << "unsigned long long " << VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000431 case Type::LongTyID:
432 return Out << "signed long long " << VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000433 case Type::UIntTyID:
Chris Lattner16c7bb22002-05-09 02:28:59 +0000434 return Out << "unsigned " << VariableName;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000435 default :
436 return Out << Ty->getDescription() << " " << VariableName;
437 }
438
439 // Check to see if the type is named.
440 map<const Type *, string>::iterator I = TypeNames.find(Ty);
441 if (I != TypeNames.end()) return Out << I->second << " " << VariableName;
442
443 // Otherwise we have a type that has not been named but is a derived type.
444 // Carefully recurse the type hierarchy to print out any contained symbolic
445 // names.
446 //
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000447 string TypeNameVar, tempstr = "";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000448 TypeNameVar = calcTypeNameVar(Ty, TypeNames, VariableName, tempstr);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000449 return Out << TypeNameVar;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000450}
451
452// Internal guts of printing a type name
453static ostream &printTypeInt(ostream &Out, const Type *Ty,
454 map<const Type *, string> &TypeNames) {
455 // Primitive types always print out their description, regardless of whether
456 // they have been named or not.
457
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000458 if (Ty->isPrimitiveType())
459 switch (Ty->getPrimitiveID()) {
460 case Type::BoolTyID:
Chris Lattner16c7bb22002-05-09 02:28:59 +0000461 return Out << "bool";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000462 case Type::UByteTyID:
463 return Out << "unsigned char";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000464 case Type::SByteTyID:
465 return Out << "signed char";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000466 case Type::UShortTyID:
Chris Lattner16c7bb22002-05-09 02:28:59 +0000467 return Out << "unsigned short";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000468 case Type::ULongTyID:
469 return Out << "unsigned long long";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000470 case Type::LongTyID:
471 return Out << "signed long long";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000472 case Type::UIntTyID:
Chris Lattner16c7bb22002-05-09 02:28:59 +0000473 return Out << "unsigned";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000474 default :
475 return Out << Ty->getDescription();
476 }
477
478 // Check to see if the type is named.
479 map<const Type *, string>::iterator I = TypeNames.find(Ty);
480 if (I != TypeNames.end()) return Out << I->second;
481
482 // Otherwise we have a type that has not been named but is a derived type.
483 // Carefully recurse the type hierarchy to print out any contained symbolic
484 // names.
485 //
Chris Lattner16c7bb22002-05-09 02:28:59 +0000486 string MInfo;
487 string TypeName = calcTypeName(Ty, TypeNames, MInfo);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000488 // TypeNames.insert(std::make_pair(Ty, TypeName));
489 //Cache type name for later use
490 if (MInfo != "")
491 return Out << TypeName << ")" << MInfo;
492 else
493 return Out << TypeName;
494}
495
496namespace {
497
498 //Internal CWriter class mimics AssemblyWriter.
499 class CWriter {
500 ostream& Out;
501 SlotCalculator &Table;
502 const Module *TheModule;
503 map<const Type *, string> TypeNames;
504 public:
505 inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
506 : Out(o), Table(Tab), TheModule(M) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000507 }
508
Chris Lattner16c7bb22002-05-09 02:28:59 +0000509 inline void write(const Module *M) { printModule(M); }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000510
511 ostream& printTypeVar(const Type *Ty, string VariableName, ostream &Out);
512 ostream& printType(const Type *Ty, ostream &Out);
513 void writeOperand(const Value *Operand, bool PrintType,ostream &Out,
514 bool PrintName = true);
515
516 private :
517 void printModule(const Module *M);
518 void printSymbolTable(const SymbolTable &ST);
519 void printConstant(const Constant *CPV);
520 void printGlobal(const GlobalVariable *GV);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000521 void printFunctionSignature(const Function *F);
522 void printFunctionDecl(const Function *F); // Print just the forward decl
523 void printFunctionArgument(const Argument *FA);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000524
525 void printFunction(const Function *);
526
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000527 void outputBasicBlock(const BasicBlock *);
528 };
529 /* END class CWriter */
530
531
532 /* CLASS InstLocalVarsVisitor */
533 class InstLocalVarsVisitor : public InstVisitor<InstLocalVarsVisitor> {
534 SlotCalculator& Table;
535
Chris Lattner16c7bb22002-05-09 02:28:59 +0000536 void handleTerminator(TerminatorInst *tI, int indx);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000537
538 public:
539 CLocalVars CLV;
540
Chris Lattner16c7bb22002-05-09 02:28:59 +0000541 InstLocalVarsVisitor(SlotCalculator& table) : Table(table) {}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000542
543 void visitInstruction(Instruction *I) {
544 string tempostr;
545 if (I && I->hasName() && !isa<PHINode>(I)) {
546 tempostr = "llvm__" + makeNameProper(I->getName()) + "_" +
547 itostr((int)I->getType()->getUniqueID());
548 CLV.addLocalVar(I->getType(), tempostr);
549 } else if (I) {
550 int Slot = Table.getValSlot(I);
551 //if (Slot < 0) then it is a instruction with no
552 // value (like return void )
553 if ((Slot >= 0) && !isa<PHINode>(I)) {
554 tempostr = "llvm__tmp_";
555 tempostr += itostr(Slot) + "_" +
556 itostr((int)I->getType()->getUniqueID());
557 CLV.addLocalVar(I->getType(), tempostr);
558 }
559 }
560
561 }
562
563 void visitBranchInst(BranchInst *I) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000564 handleTerminator(I, 0);
565 if (I->isConditional())
566 handleTerminator(I, 1);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000567 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000568 };
569
570
571 /* CLASS CInstPrintVisitor */
572
573 class CInstPrintVisitor: public InstVisitor<CInstPrintVisitor> {
574 CWriter& CW;
575 SlotCalculator& Table;
576 ostream &Out;
577 const Value *Operand;
578
579 void outputLValue(Instruction *);
580 void printPhiFromNextBlock(TerminatorInst *tI, int indx);
581
582 public:
583 CInstPrintVisitor (CWriter &cw, SlotCalculator& table, ostream& o)
584 : CW(cw), Table(table), Out(o) {
585
586 }
587
588 void visitCastInst(CastInst *I);
589 void visitCallInst(CallInst *I);
590 void visitShr(ShiftInst *I);
591 void visitShl(ShiftInst *I);
592 void visitReturnInst(ReturnInst *I);
593 void visitBranchInst(BranchInst *I);
594 void visitSwitchInst(SwitchInst *I);
595 void visitInvokeInst(InvokeInst *I) ;
596 void visitMallocInst(MallocInst *I);
597 void visitAllocaInst(AllocaInst *I);
598 void visitFreeInst(FreeInst *I);
599 void visitLoadInst(LoadInst *I);
600 void visitStoreInst(StoreInst *I);
601 void visitGetElementPtrInst(GetElementPtrInst *I);
602 void visitPHINode(PHINode *I);
603 void visitUnaryOperator (UnaryOperator *I);
604 void visitBinaryOperator(BinaryOperator *I);
605
606 };
607
608}
609
610void InstLocalVarsVisitor::handleTerminator(TerminatorInst *tI,int indx) {
611 BasicBlock *bb = tI->getSuccessor(indx);
612 BasicBlock::const_iterator insIt = bb->begin();
613 while (insIt != bb->end()) {
614 if (const PHINode *pI = dyn_cast<const PHINode>(*insIt)) {
615 //Its a phinode!
616 //Calculate the incoming index for this
617 int incindex = pI->getBasicBlockIndex(tI->getParent());
618 if (incindex != -1)
619 if (pI && pI->hasName()) {
620 string tempostr;
621 tempostr = "llvm__" + makeNameProper(pI->getName()) + "_" +
622 itostr((int)pI->getType()->getUniqueID());
623 CLV.addLocalVar(pI->getType(), tempostr) ;
624 } else {
625 string tempostr;
626 int Slot = Table.getValSlot(pI);
627 if (Slot >= 0) {
628 tempostr = "llvm__tmp_" + itostr(Slot) + "_"
629 + itostr((int)pI->getType()->getUniqueID());
630 CLV.addLocalVar(pI->getType(), tempostr);
631 }
632 }
633
634 }
635 else break;
636 insIt++;
637 }
638}
639
640/* Implementation of CInstPrintVisitor */
641
642void CInstPrintVisitor::outputLValue(Instruction *I) {
643 if (I && I->hasName() && !isa<PHINode>(I)) {
644 Out << "llvm__" << makeNameProper(I->getName()) << "_"
645 << I->getType()->getUniqueID() << " = ";
646 } else {
647 int Slot = Table.getValSlot(I);
648 //if (Slot < 0) then it is a instruction with no value (like return void )
649 if ((Slot >= 0) && !isa<PHINode>(I))
650 Out << "llvm__tmp_" << Slot << "_" << I->getType()->getUniqueID()
651 << " = ";
652 }
653}
654
655void CInstPrintVisitor::printPhiFromNextBlock(TerminatorInst *tI, int indx) {
656 BasicBlock *bb = tI->getSuccessor(indx);
657 BasicBlock::const_iterator insIt = bb->begin();
658 while (insIt != bb->end()) {
659 if (const PHINode *pI = dyn_cast<const PHINode>(*insIt)) {
660 //Its a phinode!
661 //Calculate the incoming index for this
662 int incindex = pI->getBasicBlockIndex(tI->getParent());
663 if (incindex != -1)
664 {
665 //now we have to do the printing
666 if (pI && pI->hasName()) {
667 Out << "llvm__" << makeNameProper(pI->getName()) << "_"
668 << pI->getType()->getUniqueID() << " = ";
669 } else {
670 int Slot = Table.getValSlot(pI);
671 if (Slot >= 0)
672 Out << "llvm__tmp_" << Slot << "_"
673 << pI->getType()->getUniqueID() << " = ";
674 }
675 CW.writeOperand(pI->getIncomingValue(incindex),false, Out);
676 Out << ";\n";
677 }
678 }
679 else break;
680 insIt++;
681 }
682}
683
684// Implement all "other" instructions, except for PHINode
685void CInstPrintVisitor::visitCastInst(CastInst *I) {
686 outputLValue(I);
687 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
688 Out << "(";
689 CW.printType(I->getType(), Out);
690 Out << ")";
691 CW.writeOperand(Operand, false, Out);
692 Out << ";\n";
693}
694
695void CInstPrintVisitor::visitCallInst(CallInst *I) {
696 outputLValue(I);
697 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
698 const PointerType *PTy = dyn_cast<PointerType>(Operand->getType());
699 const FunctionType *MTy = PTy
700 ? dyn_cast<FunctionType>(PTy->getElementType()):0;
701 const Type *RetTy = MTy ? MTy->getReturnType() : 0;
702
703 // If possible, print out the short form of the call instruction, but we can
704 // only do this if the first argument is a pointer to a nonvararg method,
705 // and if the value returned is not a pointer to a method.
706 //
707 if (RetTy && !MTy->isVarArg() &&
708 (!isa<PointerType>(RetTy)||
709 !isa<FunctionType>(cast<PointerType>(RetTy)))){
710 Out << " ";
711 Out << makeNameProper(Operand->getName());
712 } else {
713 Out << makeNameProper(Operand->getName());
714 }
715 Out << "(";
716 if (I->getNumOperands() > 1)
717 CW.writeOperand(I->getOperand(1), false, Out);
718 for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
719 Out << ",";
720 CW.writeOperand(I->getOperand(op), false, Out);
721 }
722
723 Out << " );\n";
724}
725
726void CInstPrintVisitor::visitShr(ShiftInst *I) {
727 outputLValue(I);
728 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
729 Out << "(";
730 CW.writeOperand(Operand, false, Out);
731 Out << " >> ";
732 Out << "(";
733 CW.writeOperand(I->getOperand(1), false, Out);
734 Out << "));\n";
735}
736
737void CInstPrintVisitor::visitShl(ShiftInst *I) {
738 outputLValue(I);
739 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
740 Out << "(";
741 CW.writeOperand(Operand, false, Out);
742 Out << " << ";
743 Out << "(";
744 CW.writeOperand(I->getOperand(1), false, Out);
745 Out << "));\n";
746}
747
748// Specific Instruction type classes... note that all of the casts are
749// neccesary because we use the instruction classes as opaque types...
750//
751void CInstPrintVisitor::visitReturnInst(ReturnInst *I) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000752 Out << "return ";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000753 if (I->getNumOperands())
754 CW.writeOperand(I->getOperand(0), false, Out);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000755 Out << ";\n";
756}
757
758void CInstPrintVisitor::visitBranchInst(BranchInst *I) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000759 TerminatorInst *tI = cast<TerminatorInst>(I);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000760 if (I->isConditional()) {
761 Out << " if (";
762 CW.writeOperand(I->getCondition(), false, Out);
763 Out << ")\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000764 printPhiFromNextBlock(tI,0);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000765 Out << " goto ";
766 CW.writeOperand(I->getOperand(0), false, Out);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000767 Out << ";\n";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000768 Out << " else\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000769 printPhiFromNextBlock(tI,1);
Chris Lattner16c7bb22002-05-09 02:28:59 +0000770 Out << " goto ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000771 CW.writeOperand(I->getOperand(1),false, Out);
772 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000773 } else {
774 printPhiFromNextBlock(tI,0);
775 Out << " goto ";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000776 CW.writeOperand(I->getOperand(0), false, Out);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000777 Out << ";\n";
778 }
779 Out << "\n";
780}
781
782void CInstPrintVisitor::visitSwitchInst(SwitchInst *I) {
783 Out << "\n";
784}
785
786void CInstPrintVisitor::visitInvokeInst(InvokeInst *I) {
787 Out << "\n";
788}
789
790void CInstPrintVisitor::visitMallocInst(MallocInst *I) {
791 outputLValue(I);
792 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
793 string tempstr = "";
794 Out << "(";
795 CW.printType(cast<const PointerType>(I->getType())->getElementType(), Out);
796 Out << "*) malloc(sizeof(";
797 CW.printTypeVar(cast<const PointerType>(I->getType())->getElementType(),
798 tempstr, Out);
799 Out << ")";
800 if (I->getNumOperands()) {
801 Out << " * " ;
802 CW.writeOperand(Operand, false, Out);
803 }
804 Out << ");";
805}
806
807void CInstPrintVisitor::visitAllocaInst(AllocaInst *I) {
808 outputLValue(I);
809 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
810 string tempstr = "";
811 Out << "(";
812 CW.printTypeVar(I->getType(), tempstr, Out);
813 Out << ") alloca(sizeof(";
814 CW.printTypeVar(cast<const PointerType>(I->getType())->getElementType(),
815 tempstr, Out);
816 Out << ")";
817 if (I->getNumOperands()) {
818 Out << " * " ;
819 CW.writeOperand(Operand, false, Out);
820 }
821 Out << ");\n";
822}
823
824void CInstPrintVisitor::visitFreeInst(FreeInst *I) {
825 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
826 Out << "free(";
827 CW.writeOperand(Operand, false, Out);
828 Out << ");\n";
829}
830
831void CInstPrintVisitor::visitLoadInst(LoadInst *I) {
832 outputLValue(I);
833 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
834 if (I->getNumOperands() <= 1) {
835 Out << "*";
836 CW.writeOperand(Operand,false, Out);
837 }
838 else {
839 //Check if it is an array type or struct type ptr!
840 int arrtype = 1;
841 const PointerType *PTy = dyn_cast<PointerType>(I->getType());
842 if (cast<const PointerType>(Operand->getType())->getElementType()->getPrimitiveID() == Type::StructTyID)
843 arrtype = 0;
844 if (arrtype && isa<GlobalValue>(Operand))
845 Out << "(&";
846 CW.writeOperand(Operand,false, Out);
847 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
848 if (i == 1) {
849 if (arrtype || !isa<GlobalValue>(Operand)) {
850 Out << "[";
851 CW.writeOperand(I->getOperand(i), false, Out);
852 Out << "]";
853 }
854 if (isa<GlobalValue>(Operand) && arrtype)
855 Out << ")";
856 }
857 else {
858 if (arrtype == 1) Out << "[";
859 else
860 Out << ".field";
861 CW.writeOperand(I->getOperand(i), false, Out);
862 if (arrtype == 1) Out << "]";
863 }
864 }
865 }
866 Out << ";\n";
867}
868
869void CInstPrintVisitor::visitStoreInst(StoreInst *I) {
870 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
871 if (I->getNumOperands() <= 2) {
872 Out << "*";
873 CW.writeOperand(I->getOperand(1), false, Out);
874 }
875 else {
876 //Check if it is an array type or struct type ptr!
877 int arrtype = 1;
878 if (cast<const PointerType>(I->getOperand(1)->getType())->getElementType()->getPrimitiveID() == Type::StructTyID)
879 arrtype = 0;
880 if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
881 Out << "(&";
882 CW.writeOperand(I->getOperand(1), false, Out);
883 for (unsigned i = 2, E = I->getNumOperands(); i != E; ++i) {
884 if (i == 2) {
885 if (arrtype || !isa<GlobalValue>(I->getOperand(1))) {
886 Out << "[";
887 CW.writeOperand(I->getOperand(i), false, Out);
888 Out << "]";
889 }
890 if (isa<GlobalValue>(I->getOperand(1)) && arrtype)
891 Out << ")";
892 }
893 else {
894 if (arrtype == 1) Out << "[";
895 else
896 Out << ".field";
897 CW.writeOperand(I->getOperand(i), false, Out);
898 if (arrtype == 1) Out << "]";
899 }
900 }
901 }
902 Out << " = ";
903 CW.writeOperand(Operand,false, Out);
904 Out << ";\n";
905}
906
907void CInstPrintVisitor::visitGetElementPtrInst(GetElementPtrInst *I) {
908 outputLValue(I);
909 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
910 Out << " &(";
911 if (I->getNumOperands() <= 1)
912 CW.writeOperand(Operand,false, Out);
913 else {
914 //Check if it is an array type or struct type ptr!
915 int arrtype = 1;
916 if ((cast<const PointerType>(Operand->getType()))->getElementType()->getPrimitiveID() == Type::StructTyID)
917 arrtype = 0;
918 if ((isa<GlobalValue>(Operand)) && arrtype)
919 Out << "(&";
920 CW.writeOperand(Operand,false, Out);
921 for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
922 if (i == 1) {
923 if (arrtype || !isa<GlobalValue>(Operand)){
924 Out << "[";
925 CW.writeOperand(I->getOperand(i), false, Out);
926 Out << "]";
927 }
928 if (isa<GlobalValue>(Operand) && arrtype)
929 Out << ")";
930 }
931 else {
932 if (arrtype == 1) Out << "[";
933 else
934 Out << ".field";
935 CW.writeOperand(I->getOperand(i), false, Out);
936 if (arrtype == 1) Out << "]";
937 }
938 }
939 }
940 Out << ");\n";
941}
942
943void CInstPrintVisitor::visitPHINode(PHINode *I) {
944
945}
946
947void CInstPrintVisitor::visitUnaryOperator (UnaryOperator *I) {
948 if (I->getOpcode() == Instruction::Not) {
949 outputLValue(I);
950 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
951 Out << "!(";
952 CW.writeOperand(Operand,false, Out);
953 Out << ");\n";
954 }
955 else {
956 Out << "<bad unary inst>\n";
957 }
958}
959
960void CInstPrintVisitor::visitBinaryOperator(BinaryOperator *I) {
961 //binary instructions, shift instructions, setCond instructions.
962 outputLValue(I);
963 Operand = I->getNumOperands() ? I->getOperand(0) : 0;
964 if (I->getType()->getPrimitiveID() == Type::PointerTyID) {
965 Out << "(";
966 CW.printType(I->getType(), Out);
967 Out << ")";
968 }
969 Out << "(";
970 if (Operand->getType()->getPrimitiveID() == Type::PointerTyID)
971 Out << "(long long)";
972 CW.writeOperand(Operand,false, Out);
973 Out << getOpcodeOperName(I);
974 // Need the extra parenthisis if the second operand is < 0
975 Out << '(';
976 if (I->getOperand(1)->getType()->getPrimitiveID() == Type::PointerTyID)
977 Out << "(long long)";
978 CW.writeOperand(I->getOperand(1),false, Out);
979 Out << ')';
980 Out << ");\n";
981}
982
983/* END : CInstPrintVisitor implementation */
984
985void CWriter::printModule(const Module *M) {
986 // printing stdlib inclusion
987 // Out << "#include <stdlib.h>\n";
988
Chris Lattner16c7bb22002-05-09 02:28:59 +0000989 // get declaration for alloca
990 Out << "/* Provide Declarations */\n"
991 << "#include <alloca.h>\n"
992
993 // Provide a definition for null if one does not already exist.
994 << "#ifndef NULL\n#define NULL 0\n#endif\n"
995 << "typedef unsigned char bool;\n"
996
997 << "\n\n/* Global Symbols */\n";
998
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000999 // Loop over the symbol table, emitting all named constants...
1000 if (M->hasSymbolTable())
1001 printSymbolTable(*M->getSymbolTable());
1002
Chris Lattner16c7bb22002-05-09 02:28:59 +00001003 Out << "\n\n/* Global Data */\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001004 for_each(M->gbegin(), M->gend(),
1005 bind_obj(this, &CWriter::printGlobal));
1006
Chris Lattner16c7bb22002-05-09 02:28:59 +00001007 // First output all the declarations of the functions as C requires Functions
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001008 // be declared before they are used.
Chris Lattner16c7bb22002-05-09 02:28:59 +00001009 //
1010 Out << "\n\n/* Function Declarations */\n";
1011 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001012
Chris Lattner16c7bb22002-05-09 02:28:59 +00001013 // Output all of the functions...
1014 Out << "\n\n/* Function Bodies */\n";
1015 for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001016}
1017
1018// prints the global constants
1019void CWriter::printGlobal(const GlobalVariable *GV) {
1020 string tempostr;
1021 if (GV->hasName())
1022 tempostr = "llvm__" + makeNameProper(GV->getName()) + "_" +
1023 itostr((int)GV->getType()->getUniqueID());
1024 if (GV->hasInternalLinkage()) Out << "static ";
1025
1026 printTypeVar(GV->getType()->getElementType(), tempostr, Out);
1027
1028 if (GV->hasInitializer()) {
1029 Out << " = " ;
1030 writeOperand(GV->getInitializer(), false, Out, false);
1031 }
1032
1033 Out << ";\n";
1034}
1035
1036// printSymbolTable - Run through symbol table looking for named constants
1037// if a named constant is found, emit it's declaration...
1038// Assuming that symbol table has only types and constants.
1039void CWriter::printSymbolTable(const SymbolTable &ST) {
1040 // GraphT G;
1041 for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
1042 SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
1043 SymbolTable::type_const_iterator End = ST.type_end(TI->first);
1044
1045 // TODO
1046 // Need to run through all the used types in the program
1047 // FindUsedTypes &FUT = new FindUsedTypes();
1048 // const std::set<const Type *> &UsedTypes = FUT.getTypes();
1049 // Filter out the structures printing forward definitions for each of them
1050 // and creating the dependency graph.
1051 // Print forward definitions to all of them
1052 // print the typedefs topologically sorted
1053
1054 // But for now we have
1055 for (; I != End; ++I) {
1056 const Value *V = I->second;
1057 if (const Constant *CPV = dyn_cast<const Constant>(V)) {
1058 printConstant(CPV);
1059 } else if (const Type *Ty = dyn_cast<const Type>(V)) {
1060 string tempostr;
1061 string tempstr = "";
1062 Out << "typedef ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001063 tempostr = "llvm__" + I->first;
Chris Lattner16c7bb22002-05-09 02:28:59 +00001064 string TypeNameVar = calcTypeNameVar(Ty, TypeNames,
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001065 tempostr, tempstr);
1066 Out << TypeNameVar << ";\n";
1067 if (!isa<PointerType>(Ty) ||
1068 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType())
1069 TypeNames.insert(std::make_pair(Ty, "llvm__"+I->first));
1070 }
1071 }
1072 }
1073}
1074
1075
1076// printConstant - Print out a constant pool entry...
1077//
1078void CWriter::printConstant(const Constant *CPV) {
1079 // TODO
1080 // Dinakar : Don't know what to do with unnamed constants
1081 // should do something about it later.
1082
1083 string tempostr;
1084 if (CPV->hasName()) {
1085 // Print out name...
1086 tempostr = "llvm__" + makeNameProper(CPV->getName()) + "_" +
1087 itostr((int)CPV->getType()->getUniqueID());
1088 } else {
1089 int Slot = Table.getValSlot(CPV); // slot number
1090 if (Slot >= 0)
1091 tempostr = "llvm__tmp_" + itostr(Slot) + "_" +
1092 itostr((int)CPV->getType()->getUniqueID());
1093 else
1094 tempostr = "<badref>";
1095 }
1096
1097 // Print out the constant type...
1098 printTypeVar(CPV->getType(), tempostr, Out);
1099
1100 Out << " = ";
1101 // Write the value out now...
1102 writeOperand(CPV, false, Out, false);
1103
1104 Out << "\n";
1105}
1106
Chris Lattner16c7bb22002-05-09 02:28:59 +00001107// printFunctionDecl - Print function declaration
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001108//
Chris Lattner16c7bb22002-05-09 02:28:59 +00001109void CWriter::printFunctionDecl(const Function *F) {
1110 printFunctionSignature(F);
1111 Out << ";\n";
1112}
1113
1114void CWriter::printFunctionSignature(const Function *F) {
1115 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001116
1117 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001118 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001119
Chris Lattner16c7bb22002-05-09 02:28:59 +00001120 // Print out the return type and name...
1121 printType(F->getReturnType(), Out);
1122 Out << " " << makeNameProper(F->getName()) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001123
Chris Lattner16c7bb22002-05-09 02:28:59 +00001124 if (!F->isExternal()) {
1125 for_each(F->getArgumentList().begin(), F->getArgumentList().end(),
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001126 bind_obj(this, &CWriter::printFunctionArgument));
1127 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001128 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001129 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +00001130 FT->getParamTypes().begin(),
1131 E = FT->getParamTypes().end(); I != E; ++I) {
1132 if (I != FT->getParamTypes().begin()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001133 printType(*I, Out);
1134 }
1135 }
1136
1137 // Finish printing arguments...
Chris Lattner16c7bb22002-05-09 02:28:59 +00001138 if (FT->isVarArg()) {
1139 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001140 Out << "..."; // Output varargs portion of signature!
1141 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001142 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001143}
1144
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001145
1146// printFunctionArgument - This member is called for every argument that
1147// is passed into the method. Simply print it out
1148//
1149void CWriter::printFunctionArgument(const Argument *Arg) {
1150 // Insert commas as we go... the first arg doesn't get a comma
1151 string tempostr;
1152 if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
1153
1154 // Output name, if available...
1155 if (Arg->hasName()) {
1156 tempostr = "llvm__" + makeNameProper(Arg->getName()) + "_" +
1157 itostr((int)Arg->getType()->getUniqueID());
1158 } else if (Table.getValSlot(Arg) < 0) {
1159 tempostr = "<badref>";
1160 }
1161 else {
1162 tempostr = "llvm__tmp_" + itostr(Table.getValSlot(Arg)) + "_" +
1163 itostr((int)Arg->getType()->getUniqueID());
1164 }
1165 // Output type...
1166 // printType(Arg->getType(), Out);
1167 // Out << " " << tempostr;
1168 printTypeVar (Arg->getType(), tempostr, Out);
1169}
1170
Chris Lattner16c7bb22002-05-09 02:28:59 +00001171void CWriter::printFunction(const Function *F) {
1172 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001173
Chris Lattner16c7bb22002-05-09 02:28:59 +00001174 // Process each of the basic blocks, gather information and call the
1175 // output methods on the CLocalVars and Function* objects.
1176
1177 // gather local variable information for each basic block
1178 InstLocalVarsVisitor ILV(Table);
1179 ILV.visit((Function *)F);
1180
1181 printFunctionSignature(F);
1182 Out << " {\n";
1183
1184 // Loop over the symbol table, emitting all named constants...
1185 if (F->hasSymbolTable())
1186 printSymbolTable(*F->getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001187
Chris Lattner16c7bb22002-05-09 02:28:59 +00001188 // print the local variables
1189 // we assume that every local variable is alloca'ed in the C code.
1190 std::map<const Type*, VarListType> &locals = ILV.CLV.LocalVars;
1191
1192 map<const Type*, VarListType>::iterator iter;
1193 for (iter = locals.begin(); iter != locals.end(); ++iter) {
1194 VarListType::iterator listiter;
1195 for (listiter = iter->second.begin(); listiter != iter->second.end();
1196 ++listiter) {
1197 Out << " ";
1198 printTypeVar(iter->first, *listiter, Out);
1199 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001200 }
1201 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001202
1203 // print the basic blocks
1204 for_each(F->begin(), F->end(), bind_obj(this, &CWriter::outputBasicBlock));
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001205
Chris Lattner16c7bb22002-05-09 02:28:59 +00001206 Out << "}\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001207}
1208
1209void CWriter::outputBasicBlock(const BasicBlock* BB) {
1210
1211 if (BB->hasName()) { // Print out the label if it exists...
1212 Out << "llvm__" << makeNameProper(BB->getName()) << "_"
1213 << BB->getType()->getUniqueID() << ":\n";
1214 } else {
1215 int Slot = Table.getValSlot(BB);
1216 Out << "llvm__tmp_";
1217 if (Slot >= 0)
1218 Out << Slot << "_" << BB->getType()->getUniqueID() << ":\n";
1219 // Extra newline seperates out label's
1220 else
1221 Out << "<badref>\n";
1222 }
1223
1224 // Output all of the instructions in the basic block...
1225 // print the basic blocks
1226 CInstPrintVisitor CIPV(*this, Table, Out);
1227 CIPV.visit((BasicBlock *) BB);
1228}
1229
1230// printTypeVar - Go to extreme measures to attempt to print out a short,
1231// symbolic version of a type name.
1232//
1233ostream& CWriter::printTypeVar(const Type *Ty, string VariableName,
1234 ostream &Out) {
1235 return printTypeVarInt(Out, Ty, TypeNames, VariableName);
1236}
1237
1238// printType - Go to extreme measures to attempt to print out a short, symbolic
1239// version of a type name.
1240ostream& CWriter::printType(const Type *Ty, ostream &Out) {
1241 return printTypeInt(Out, Ty, TypeNames);
1242}
1243
1244
1245void CWriter::writeOperand(const Value *Operand, bool PrintType,
Chris Lattner16c7bb22002-05-09 02:28:59 +00001246 ostream &Out, bool PrintName = true) {
1247 if (PrintType) {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001248 Out << " ";
1249 printType(Operand->getType(), Out);
1250 }
Chris Lattner16c7bb22002-05-09 02:28:59 +00001251
1252 if (PrintName && Operand->hasName()) {
1253 // If Operand has a name.
1254 Out << "llvm__" << makeNameProper(Operand->getName()) << "_" <<
1255 Operand->getType()->getUniqueID();
1256 return;
1257 }
1258 else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
1259 if (isa<ConstantPointerNull>(CPV))
1260 Out << "NULL";
1261 else
1262 Out << getConstStrValue(CPV);
1263 }
1264 else {
1265 int Slot = Table.getValSlot(Operand);
1266 if (Slot >= 0)
1267 Out << "llvm__tmp_" << Slot << "_" << Operand->getType()->getUniqueID();
1268 else if (PrintName)
1269 Out << "<badref>";
1270 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001271}
1272
1273
1274//===----------------------------------------------------------------------===//
1275// External Interface declaration
1276//===----------------------------------------------------------------------===//
1277
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001278void WriteToC(const Module *C, ostream &Out) {
1279 assert(C && "You can't write a null module!!");
1280 SlotCalculator SlotTable(C, true);
1281 CWriter W(Out, SlotTable, C);
1282 W.write(C);
1283 Out.flush();
1284}
1285