blob: 4227114b154d93e33800d99d6b3291da0fc3fc3f [file] [log] [blame]
Chris Lattner3af3ba82002-05-09 21:31:18 +00001//===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00002//
Chris Lattnerd1cf1b42002-09-20 23:26:33 +00003// This library converts LLVM code to C code, compilable by GCC.
Chris Lattner16c7bb22002-05-09 02:28:59 +00004//
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00005//===-----------------------------------------------------------------------==//
6#include "llvm/Assembly/CWriter.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00007#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +00008#include "llvm/DerivedTypes.h"
9#include "llvm/Module.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000010#include "llvm/iMemory.h"
11#include "llvm/iTerminators.h"
12#include "llvm/iPHINode.h"
13#include "llvm/iOther.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +000014#include "llvm/iOperators.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000015#include "llvm/Pass.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000016#include "llvm/SymbolTable.h"
Chris Lattner3af3ba82002-05-09 21:31:18 +000017#include "llvm/SlotCalculator.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000018#include "llvm/Analysis/FindUsedTypes.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000019#include "llvm/Analysis/ConstantsScanner.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000020#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000021#include "llvm/Support/InstIterator.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000022#include "Support/StringExtras.h"
23#include "Support/STLExtras.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000024#include <algorithm>
Chris Lattner78771c82002-05-17 04:55:35 +000025#include <set>
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000026using std::string;
27using std::map;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000028using std::ostream;
29
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000030
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000031namespace {
Chris Lattner0e9f93e2002-08-31 00:29:16 +000032 class CWriter : public Pass, public InstVisitor<CWriter> {
33 ostream &Out;
34 SlotCalculator *Table;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000035 const Module *TheModule;
36 map<const Type *, string> TypeNames;
Chris Lattner78771c82002-05-17 04:55:35 +000037 std::set<const Value*> MangledGlobals;
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000038 bool needsMalloc;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000039
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000040 map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000041 public:
Chris Lattner0e9f93e2002-08-31 00:29:16 +000042 CWriter(ostream &o) : Out(o) {}
43
44 void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.setPreservesAll();
46 AU.addRequired<FindUsedTypes>();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000047 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000048
49 virtual bool run(Module &M) {
50 // Initialize
51 Table = new SlotCalculator(&M, false);
52 TheModule = &M;
53
54 // Ensure that all structure types have names...
55 bool Changed = nameAllUsedStructureTypes(M);
56
57 // Run...
58 printModule(&M);
59
60 // Free memory...
61 delete Table;
62 TypeNames.clear();
63 MangledGlobals.clear();
64 return false;
65 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000066
Chris Lattner83c57752002-08-19 22:17:53 +000067 ostream &printType(const Type *Ty, const string &VariableName = "",
Vikram S. Adve969c4ad2002-08-25 20:00:08 +000068 bool IgnoreName = false, bool namedContext = true);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000069
Chris Lattnerbb03efd2002-06-25 15:57:03 +000070 void writeOperand(Value *Operand);
71 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000072
73 string getValueName(const Value *V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000074
Chris Lattner4fbf26d2002-05-09 20:53:56 +000075 private :
Chris Lattner0e9f93e2002-08-31 00:29:16 +000076 bool nameAllUsedStructureTypes(Module &M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000077 void printModule(Module *M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000078 void printSymbolTable(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +000079 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000080 void printGlobal(const GlobalVariable *GV);
Chris Lattner4cda8352002-08-20 16:55:48 +000081 void printFunctionSignature(const Function *F, bool Prototype);
82
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000083 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000084
Chris Lattner6d492922002-08-19 21:32:41 +000085 void printConstant(Constant *CPV);
86 void printConstantArray(ConstantArray *CPA);
87
Chris Lattnerd0c668c2002-05-09 21:18:38 +000088 // isInlinableInst - Attempt to inline instructions into their uses to build
89 // trees as much as possible. To do this, we have to consistently decide
90 // what is acceptable to inline, so that variable declarations don't get
91 // printed and an extra copy of the expr is not emitted.
92 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +000093 static bool isInlinableInst(const Instruction &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +000094 // Must be an expression, must be used exactly once. If it is dead, we
95 // emit it inline where it would go.
Chris Lattnerbb03efd2002-06-25 15:57:03 +000096 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
Chris Lattnerd0c668c2002-05-09 21:18:38 +000097 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
98 return false;
99
100 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000101 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000102 }
103
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000104 // Instruction visitation functions
105 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000106
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000107 void visitReturnInst(ReturnInst &I);
108 void visitBranchInst(BranchInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000109
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000110 void visitPHINode(PHINode &I) {}
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000111 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000112
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000113 void visitCastInst (CastInst &I);
114 void visitCallInst (CallInst &I);
115 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000116
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000117 void visitMallocInst(MallocInst &I);
118 void visitAllocaInst(AllocaInst &I);
119 void visitFreeInst (FreeInst &I);
120 void visitLoadInst (LoadInst &I);
121 void visitStoreInst (StoreInst &I);
122 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000123
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000124 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000125 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000126 abort();
127 }
128
129 void outputLValue(Instruction *I) {
130 Out << " " << getValueName(I) << " = ";
131 }
132 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
133 unsigned Indent);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000134 void printIndexingExpression(Value *Ptr, User::op_iterator I,
135 User::op_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000136 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000137}
138
Chris Lattner2f499022002-05-09 04:21:21 +0000139// We dont want identifier names with ., space, - in them.
140// So we replace them with _
141static string makeNameProper(string x) {
142 string tmp;
143 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
144 switch (*sI) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000145 case '.': tmp += "d_"; break;
146 case ' ': tmp += "s_"; break;
147 case '-': tmp += "D_"; break;
Chris Lattner2f499022002-05-09 04:21:21 +0000148 default: tmp += *sI;
149 }
150
151 return tmp;
152}
153
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000154string CWriter::getValueName(const Value *V) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000155 if (V->hasName()) { // Print out the label if it exists...
156 if (isa<GlobalValue>(V) && // Do not mangle globals...
157 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
158 !MangledGlobals.count(V)) // Unless the name would collide if we don't
Chris Lattner2f499022002-05-09 04:21:21 +0000159 return makeNameProper(V->getName());
160
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000161 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
162 makeNameProper(V->getName());
Chris Lattner2f499022002-05-09 04:21:21 +0000163 }
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000164
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000165 int Slot = Table->getValSlot(V);
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000166 assert(Slot >= 0 && "Invalid value!");
Chris Lattner2d05a1a2002-05-09 05:16:40 +0000167 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000168}
169
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000170// A pointer type should not use parens around *'s alone, e.g., (**)
171inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
172 return (NameSoFar.find_last_not_of('*') != std::string::npos);
173}
174
Chris Lattner83c57752002-08-19 22:17:53 +0000175// Pass the Type* and the variable name and this prints out the variable
176// declaration.
177//
178ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000179 bool IgnoreName, bool namedContext) {
Chris Lattner83c57752002-08-19 22:17:53 +0000180 if (Ty->isPrimitiveType())
181 switch (Ty->getPrimitiveID()) {
182 case Type::VoidTyID: return Out << "void " << NameSoFar;
183 case Type::BoolTyID: return Out << "bool " << NameSoFar;
184 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
185 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
186 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
187 case Type::ShortTyID: return Out << "short " << NameSoFar;
188 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
189 case Type::IntTyID: return Out << "int " << NameSoFar;
190 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
191 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
192 case Type::FloatTyID: return Out << "float " << NameSoFar;
193 case Type::DoubleTyID: return Out << "double " << NameSoFar;
194 default :
195 std::cerr << "Unknown primitive type: " << Ty << "\n";
196 abort();
197 }
198
199 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000200 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattner83c57752002-08-19 22:17:53 +0000201 map<const Type *, string>::iterator I = TypeNames.find(Ty);
202 if (I != TypeNames.end()) {
203 return Out << I->second << " " << NameSoFar;
204 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000205 }
Chris Lattner83c57752002-08-19 22:17:53 +0000206
Chris Lattner83c57752002-08-19 22:17:53 +0000207 switch (Ty->getPrimitiveID()) {
208 case Type::FunctionTyID: {
209 const FunctionType *MTy = cast<FunctionType>(Ty);
210 printType(MTy->getReturnType(), "");
211 Out << " " << NameSoFar << " (";
212
213 for (FunctionType::ParamTypes::const_iterator
214 I = MTy->getParamTypes().begin(),
215 E = MTy->getParamTypes().end(); I != E; ++I) {
216 if (I != MTy->getParamTypes().begin())
217 Out << ", ";
218 printType(*I, "");
219 }
220 if (MTy->isVarArg()) {
221 if (!MTy->getParamTypes().empty())
222 Out << ", ";
223 Out << "...";
224 }
225 return Out << ")";
226 }
227 case Type::StructTyID: {
228 const StructType *STy = cast<StructType>(Ty);
229 Out << NameSoFar + " {\n";
230 unsigned Idx = 0;
231 for (StructType::ElementTypes::const_iterator
232 I = STy->getElementTypes().begin(),
233 E = STy->getElementTypes().end(); I != E; ++I) {
234 Out << " ";
235 printType(*I, "field" + utostr(Idx++));
236 Out << ";\n";
237 }
238 return Out << "}";
239 }
240
241 case Type::PointerTyID: {
242 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000243 std::string ptrName = "*" + NameSoFar;
244
245 // Do not need parens around "* NameSoFar" if NameSoFar consists only
246 // of zero or more '*' chars *and* this is not an unnamed pointer type
247 // such as the result type in a cast statement. Otherwise, enclose in ( ).
Nick Hildenbrandtc14ded42002-09-23 21:02:50 +0000248 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
249 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000250 ptrName = "(" + ptrName + ")"; //
251
Vikram S. Adve42eb2ba2002-08-24 14:44:23 +0000252 return printType(PTy->getElementType(), ptrName);
Chris Lattner83c57752002-08-19 22:17:53 +0000253 }
254
255 case Type::ArrayTyID: {
256 const ArrayType *ATy = cast<ArrayType>(Ty);
257 unsigned NumElements = ATy->getNumElements();
258 return printType(ATy->getElementType(),
259 NameSoFar + "[" + utostr(NumElements) + "]");
260 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000261
262 case Type::OpaqueTyID: {
263 static int Count = 0;
264 string TyName = "struct opaque_" + itostr(Count++);
265 assert(TypeNames.find(Ty) == TypeNames.end());
266 TypeNames[Ty] = TyName;
267 return Out << TyName << " " << NameSoFar;
268 }
Chris Lattner83c57752002-08-19 22:17:53 +0000269 default:
270 assert(0 && "Unhandled case in getTypeProps!");
271 abort();
272 }
273
274 return Out;
275}
276
Chris Lattner6d492922002-08-19 21:32:41 +0000277void CWriter::printConstantArray(ConstantArray *CPA) {
278
279 // As a special case, print the array as a string if it is an array of
280 // ubytes or an array of sbytes with positive values.
281 //
282 const Type *ETy = CPA->getType()->getElementType();
283 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
284
285 // Make sure the last character is a null char, as automatically added by C
286 if (CPA->getNumOperands() == 0 ||
287 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
288 isString = false;
289
290 if (isString) {
291 Out << "\"";
292 // Do not include the last character, which we know is null
293 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
294 unsigned char C = (ETy == Type::SByteTy) ?
295 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
296 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
297
298 if (isprint(C)) {
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000299 if (C == '"')
300 Out << "\\\"";
301 else
302 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000303 } else {
304 switch (C) {
305 case '\n': Out << "\\n"; break;
306 case '\t': Out << "\\t"; break;
307 case '\r': Out << "\\r"; break;
308 case '\v': Out << "\\v"; break;
309 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000310 case '\"': Out << "\\\""; break;
311 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000312 default:
313 Out << "\\x";
314 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
315 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
316 break;
317 }
318 }
319 }
320 Out << "\"";
321 } else {
322 Out << "{";
323 if (CPA->getNumOperands()) {
324 Out << " ";
325 printConstant(cast<Constant>(CPA->getOperand(0)));
326 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
327 Out << ", ";
328 printConstant(cast<Constant>(CPA->getOperand(i)));
329 }
330 }
331 Out << " }";
332 }
333}
334
335
336// printConstant - The LLVM Constant to C Constant converter.
337void CWriter::printConstant(Constant *CPV) {
338 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
339 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000340 case Instruction::Cast:
341 Out << "((";
342 printType(CPV->getType());
343 Out << ")";
344 printConstant(cast<Constant>(CPV->getOperand(0)));
345 Out << ")";
346 return;
347
348 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000349 Out << "(&(";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000350 printIndexingExpression(CPV->getOperand(0),
351 CPV->op_begin()+1, CPV->op_end());
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000352 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000353 return;
354 case Instruction::Add:
355 Out << "(";
356 printConstant(cast<Constant>(CPV->getOperand(0)));
357 Out << " + ";
358 printConstant(cast<Constant>(CPV->getOperand(1)));
359 Out << ")";
360 return;
361 case Instruction::Sub:
362 Out << "(";
363 printConstant(cast<Constant>(CPV->getOperand(0)));
364 Out << " - ";
365 printConstant(cast<Constant>(CPV->getOperand(1)));
366 Out << ")";
367 return;
368
Chris Lattner6d492922002-08-19 21:32:41 +0000369 default:
370 std::cerr << "CWriter Error: Unhandled constant expression: "
371 << CE << "\n";
372 abort();
373 }
374 }
375
376 switch (CPV->getType()->getPrimitiveID()) {
377 case Type::BoolTyID:
378 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
379 case Type::SByteTyID:
380 case Type::ShortTyID:
381 case Type::IntTyID:
382 Out << cast<ConstantSInt>(CPV)->getValue(); break;
383 case Type::LongTyID:
384 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
385
386 case Type::UByteTyID:
387 case Type::UShortTyID:
388 Out << cast<ConstantUInt>(CPV)->getValue(); break;
389 case Type::UIntTyID:
390 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
391 case Type::ULongTyID:
392 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
393
394 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000395 case Type::DoubleTyID: {
396 ConstantFP *FPC = cast<ConstantFP>(CPV);
397 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
398 if (I != FPConstantMap.end()) {
399 // Because of FP precision problems we must load from a stack allocated
400 // value that holds the value in hex.
401 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
402 << "*)&FloatConstant" << I->second << ")";
403 } else {
404 Out << FPC->getValue();
405 }
406 break;
407 }
Chris Lattner6d492922002-08-19 21:32:41 +0000408
409 case Type::ArrayTyID:
410 printConstantArray(cast<ConstantArray>(CPV));
411 break;
412
413 case Type::StructTyID: {
414 Out << "{";
415 if (CPV->getNumOperands()) {
416 Out << " ";
417 printConstant(cast<Constant>(CPV->getOperand(0)));
418 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
419 Out << ", ";
420 printConstant(cast<Constant>(CPV->getOperand(i)));
421 }
422 }
423 Out << " }";
424 break;
425 }
426
427 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000428 if (isa<ConstantPointerNull>(CPV)) {
429 Out << "((";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000430 printType(CPV->getType(), "");
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000431 Out << ")NULL)";
Chris Lattner6d492922002-08-19 21:32:41 +0000432 break;
433 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
434 writeOperand(CPR->getValue());
435 break;
436 }
437 // FALL THROUGH
438 default:
439 std::cerr << "Unknown constant type: " << CPV << "\n";
440 abort();
441 }
442}
443
444void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000445 if (Instruction *I = dyn_cast<Instruction>(Operand))
446 if (isInlinableInst(*I)) {
447 // Should we inline this instruction to build a tree?
448 Out << "(";
449 visit(*I);
450 Out << ")";
451 return;
452 }
453
Chris Lattner6d492922002-08-19 21:32:41 +0000454 if (Operand->hasName()) {
455 Out << getValueName(Operand);
456 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
457 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000458 } else {
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000459 int Slot = Table->getValSlot(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000460 assert(Slot >= 0 && "Malformed LLVM!");
461 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
462 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000463}
464
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000465void CWriter::writeOperand(Value *Operand) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000466 if (isa<GlobalVariable>(Operand))
467 Out << "(&"; // Global variables are references as their addresses by llvm
468
469 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000470
471 if (isa<GlobalVariable>(Operand))
472 Out << ")";
473}
474
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000475// nameAllUsedStructureTypes - If there are structure types in the module that
476// are used but do not have names assigned to them in the symbol table yet then
477// we assign them names now.
478//
479bool CWriter::nameAllUsedStructureTypes(Module &M) {
480 // Get a set of types that are used by the program...
481 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
482
483 // Loop over the module symbol table, removing types from UT that are already
484 // named.
485 //
486 SymbolTable *MST = M.getSymbolTableSure();
487 if (MST->find(Type::TypeTy) != MST->end())
488 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
489 E = MST->type_end(Type::TypeTy); I != E; ++I)
490 UT.erase(cast<Type>(I->second));
491
492 // UT now contains types that are not named. Loop over it, naming structure
493 // types.
494 //
495 bool Changed = false;
496 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
497 I != E; ++I)
498 if (const StructType *ST = dyn_cast<StructType>(*I)) {
499 ((Value*)ST)->setName("unnamed", MST);
500 Changed = true;
501 }
502 return Changed;
503}
504
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000505void CWriter::printModule(Module *M) {
Chris Lattner78771c82002-05-17 04:55:35 +0000506 // Calculate which global values have names that will collide when we throw
507 // away type information.
Chris Lattner594b9fa2002-05-21 21:10:04 +0000508 { // Scope to delete the FoundNames set when we are done with it...
Chris Lattner78771c82002-05-17 04:55:35 +0000509 std::set<string> FoundNames;
510 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000511 if (I->hasName()) // If the global has a name...
512 if (FoundNames.count(I->getName())) // And the name is already used
513 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000514 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000515 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000516
517 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000518 if (I->hasName()) // If the global has a name...
519 if (FoundNames.count(I->getName())) // And the name is already used
520 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000521 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000522 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000523 }
524
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000525 // printing stdlib inclusion
Nick Hildenbrandt98360a12002-10-11 21:40:44 +0000526 //Out << "#include <stdlib.h>\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000527
Chris Lattner16c7bb22002-05-09 02:28:59 +0000528 // get declaration for alloca
529 Out << "/* Provide Declarations */\n"
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000530 << "#include <alloca.h>\n\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000531
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000532 // Provide a definition for null if one does not already exist,
533 // and for `bool' if not compiling with a C++ compiler.
Chris Lattnerb5af06a2002-05-09 03:06:06 +0000534 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000535 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Chris Lattner16c7bb22002-05-09 02:28:59 +0000536
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000537 << "\n\n/* Support for floating point constants */\n"
538 << "typedef unsigned long long ConstantDoubleTy;\n"
539
Chris Lattnera4d4a852002-08-19 21:48:40 +0000540 << "\n\n/* Global Declarations */\n";
541
542 // First output all the declarations for the program, because C requires
543 // Functions & globals to be declared before they are used.
544 //
Chris Lattner16c7bb22002-05-09 02:28:59 +0000545
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000546 // Loop over the symbol table, emitting all named constants...
547 if (M->hasSymbolTable())
548 printSymbolTable(*M->getSymbolTable());
549
Chris Lattnera4d4a852002-08-19 21:48:40 +0000550 // Global variable declarations...
551 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000552 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000553 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000554 if (I->hasExternalLinkage()) {
555 Out << "extern ";
556 printType(I->getType()->getElementType(), getValueName(I));
557 Out << ";\n";
558 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000559 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000560 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000561
Chris Lattnera4d4a852002-08-19 21:48:40 +0000562 // Function declarations
563 if (!M->empty()) {
564 Out << "\n/* Function Declarations */\n";
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000565 needsMalloc = true;
Chris Lattner4cda8352002-08-20 16:55:48 +0000566 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
567 printFunctionSignature(I, true);
568 Out << ";\n";
569 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000570 }
571
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000572 // Print Malloc prototype if needed
573 if (needsMalloc){
574 Out << "\n/* Malloc to make sun happy */\n";
575 Out << "extern void * malloc(size_t);\n\n";
576 }
577
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000578 // Output the global variable definitions and contents...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000579 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000580 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnere8e035b2002-10-16 20:08:47 +0000581 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
582 if (!I->isExternal()) {
583 if (I->hasInternalLinkage())
584 Out << "static ";
585 printType(I->getType()->getElementType(), getValueName(I));
Chris Lattnera4d4a852002-08-19 21:48:40 +0000586
Chris Lattnera4d4a852002-08-19 21:48:40 +0000587 Out << " = " ;
588 writeOperand(I->getInitializer());
Chris Lattnere8e035b2002-10-16 20:08:47 +0000589 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000590 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000591 }
592
Chris Lattner16c7bb22002-05-09 02:28:59 +0000593 // Output all of the functions...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000594 if (!M->empty()) {
595 Out << "\n\n/* Function Bodies */\n";
596 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
597 printFunction(I);
598 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000599}
600
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000601
Chris Lattner2db41cd2002-09-20 15:12:13 +0000602/// printSymbolTable - Run through symbol table looking for type names. If a
603/// type name is found, emit it's declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000604///
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000605void CWriter::printSymbolTable(const SymbolTable &ST) {
Chris Lattner2db41cd2002-09-20 15:12:13 +0000606 // If there are no type names, exit early.
607 if (ST.find(Type::TypeTy) == ST.end())
608 return;
609
610 // We are only interested in the type plane of the symbol table...
611 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
612 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
613
Chris Lattner58d04d42002-09-20 15:18:30 +0000614 // Print out forward declarations for structure types before anything else!
615 Out << "/* Structure forward decls */\n";
616 for (; I != End; ++I)
617 if (const Type *STy = dyn_cast<StructType>(I->second)) {
618 string Name = "struct l_" + makeNameProper(I->first);
619 Out << Name << ";\n";
620 TypeNames.insert(std::make_pair(STy, Name));
621 }
622
623 Out << "\n";
624
625 // Now we can print out typedefs...
626 Out << "/* Typedefs */\n";
627 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
628 const Type *Ty = cast<Type>(I->second);
629 string Name = "l_" + makeNameProper(I->first);
630 Out << "typedef ";
Chris Lattner270d78a2002-09-20 15:20:24 +0000631 printType(Ty, Name);
Chris Lattner58d04d42002-09-20 15:18:30 +0000632 Out << ";\n";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000633 }
634
635 Out << "\n";
636
Chris Lattner2c601a72002-09-20 15:05:40 +0000637 // Keep track of which structures have been printed so far...
638 std::set<const StructType *> StructPrinted;
639
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000640 // Loop over all structures then push them into the stack so they are
641 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +0000642 //
Chris Lattner58d04d42002-09-20 15:18:30 +0000643 Out << "/* Structure contents */\n";
Chris Lattner2db41cd2002-09-20 15:12:13 +0000644 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
645 if (const StructType *STy = dyn_cast<StructType>(I->second))
646 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000647}
648
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000649// Push the struct onto the stack and recursively push all structs
650// this one depends on.
Chris Lattner2c601a72002-09-20 15:05:40 +0000651void CWriter::printContainedStructs(const Type *Ty,
652 std::set<const StructType*> &StructPrinted){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000653 if (const StructType *STy = dyn_cast<StructType>(Ty)){
654 //Check to see if we have already printed this struct
Chris Lattner2c601a72002-09-20 15:05:40 +0000655 if (StructPrinted.count(STy) == 0) {
656 // Print all contained types first...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000657 for (StructType::ElementTypes::const_iterator
658 I = STy->getElementTypes().begin(),
659 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner2c601a72002-09-20 15:05:40 +0000660 const Type *Ty1 = I->get();
Chris Lattnera4c047e2002-09-20 14:56:54 +0000661 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000662 printContainedStructs(Ty1, StructPrinted);
Chris Lattnera4c047e2002-09-20 14:56:54 +0000663 }
664
Chris Lattner2c601a72002-09-20 15:05:40 +0000665 //Print structure type out..
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000666 StructPrinted.insert(STy);
667 string Name = TypeNames[STy];
668 printType(STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +0000669 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000670 }
Chris Lattnera4c047e2002-09-20 14:56:54 +0000671
Chris Lattner2c601a72002-09-20 15:05:40 +0000672 // If it is an array, check contained types and continue
673 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000674 const Type *Ty1 = ATy->getElementType();
675 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000676 printContainedStructs(Ty1, StructPrinted);
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000677 }
678}
679
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000680
Chris Lattner4cda8352002-08-20 16:55:48 +0000681void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000682 // If the program provides it's own malloc prototype we don't need
683 // to include the general one.
684 if (getValueName(F) == "malloc")
685 needsMalloc = false;
Chris Lattner16c7bb22002-05-09 02:28:59 +0000686 if (F->hasInternalLinkage()) Out << "static ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000687
688 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000689 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000690
Chris Lattner16c7bb22002-05-09 02:28:59 +0000691 // Print out the return type and name...
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000692 printType(F->getReturnType());
Chris Lattner1f02c892002-05-09 20:14:10 +0000693 Out << getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000694
Chris Lattner16c7bb22002-05-09 02:28:59 +0000695 if (!F->isExternal()) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000696 if (!F->aempty()) {
Chris Lattner4cda8352002-08-20 16:55:48 +0000697 string ArgName;
698 if (F->abegin()->hasName() || !Prototype)
699 ArgName = getValueName(F->abegin());
700
701 printType(F->afront().getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000702
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000703 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
704 I != E; ++I) {
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000705 Out << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +0000706 if (I->hasName() || !Prototype)
707 ArgName = getValueName(I);
708 else
709 ArgName = "";
710 printType(I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000711 }
712 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000713 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000714 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000715 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000716 FT->getParamTypes().begin(),
717 E = FT->getParamTypes().end(); I != E; ++I) {
718 if (I != FT->getParamTypes().begin()) Out << ", ";
Chris Lattner2a7ab2e2002-05-09 04:39:00 +0000719 printType(*I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000720 }
721 }
722
Chris Lattner1f8c4a12002-09-20 22:32:30 +0000723 // Finish printing arguments... if this is a vararg function, print the ...,
724 // unless there are no known types, in which case, we just emit ().
725 //
726 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000727 if (FT->getParamTypes().size()) Out << ", ";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000728 Out << "..."; // Output varargs portion of signature!
729 }
Chris Lattner16c7bb22002-05-09 02:28:59 +0000730 Out << ")";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000731}
732
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000733
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000734void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000735 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000736
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000737 Table->incorporateFunction(F);
Chris Lattnerf34ee812002-05-09 03:12:34 +0000738
Chris Lattner4cda8352002-08-20 16:55:48 +0000739 printFunctionSignature(F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000740 Out << " {\n";
741
Chris Lattner497e19a2002-05-09 20:39:03 +0000742 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000743 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000744 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000745 Out << " ";
Chris Lattner3af3ba82002-05-09 21:31:18 +0000746 printType((*I)->getType(), getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000747 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000748 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000749
750 Out << "\n";
751
752 // Scan the function for floating point constants. If any FP constant is used
753 // in the function, we want to redirect it here so that we do not depend on
754 // the precision of the printed form.
755 //
756 unsigned FPCounter = 0;
757 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
758 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
759 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
760 double Val = FPC->getValue();
761
762 FPConstantMap[FPC] = FPCounter; // Number the FP constants
763 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
764 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
765 << "; /* " << Val << " */\n";
766 }
767
768 Out << "\n";
Chris Lattner16c7bb22002-05-09 02:28:59 +0000769
770 // print the basic blocks
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000771 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
772 BasicBlock *Prev = BB->getPrev();
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000773
774 // Don't print the label for the basic block if there are no uses, or if the
775 // only terminator use is the precessor basic block's terminator. We have
776 // to scan the use list because PHI nodes use basic blocks too but do not
777 // require a label to be generated.
778 //
779 bool NeedsLabel = false;
780 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
781 UI != UE; ++UI)
782 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
783 if (TI != Prev->getTerminator()) {
784 NeedsLabel = true;
785 break;
786 }
787
788 if (NeedsLabel) Out << getValueName(BB) << ":\n";
789
790 // Output all of the instructions in the basic block...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000791 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000792 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000793 if (II->getType() != Type::VoidTy)
794 outputLValue(II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000795 else
796 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000797 visit(*II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000798 Out << ";\n";
799 }
800 }
801
802 // Don't emit prefix or suffix for the terminator...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000803 visit(*BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000804 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000805
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000806 Out << "}\n\n";
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000807 Table->purgeFunction();
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000808 FPConstantMap.clear();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000809}
810
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000811// Specific Instruction type classes... note that all of the casts are
812// neccesary because we use the instruction classes as opaque types...
813//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000814void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000815 // Don't output a void return if this is the last basic block in the function
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000816 if (I.getNumOperands() == 0 &&
817 &*--I.getParent()->getParent()->end() == I.getParent() &&
818 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000819 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000820 }
Chris Lattner44408262002-05-09 03:50:42 +0000821
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000822 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000823 if (I.getNumOperands()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000824 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000825 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000826 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000827 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000828}
829
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000830static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
831 // If PHI nodes need copies, we need the copy code...
832 if (isa<PHINode>(To->front()) ||
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000833 From->getNext() != To) // Not directly successor, need goto
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000834 return true;
835
836 // Otherwise we don't need the code.
837 return false;
838}
839
840void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
841 unsigned Indent) {
842 for (BasicBlock::iterator I = Succ->begin();
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000843 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000844 // now we have to do the printing
845 Out << string(Indent, ' ');
846 outputLValue(PN);
847 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
848 Out << "; /* for PHI node */\n";
849 }
850
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000851 if (CurBB->getNext() != Succ) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000852 Out << string(Indent, ' ') << " goto ";
853 writeOperand(Succ);
854 Out << ";\n";
855 }
856}
857
858// Brach instruction printing - Avoid printing out a brach to a basic block that
859// immediately succeeds the current one.
860//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000861void CWriter::visitBranchInst(BranchInst &I) {
862 if (I.isConditional()) {
863 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000864 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000865 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000866 Out << ") {\n";
867
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000868 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000869
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000870 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000871 Out << " } else {\n";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000872 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000873 }
874 } else {
875 // First goto not neccesary, assume second one is...
876 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000877 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000878 Out << ") {\n";
879
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000880 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000881 }
882
883 Out << " }\n";
884 } else {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000885 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000886 }
887 Out << "\n";
888}
889
890
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000891void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000892 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000893 if (isa<PointerType>(I.getType())) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000894 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000895 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000896 Out << ")";
897 }
898
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000899 if (isa<PointerType>(I.getType())) Out << "(long long)";
900 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000901
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000902 switch (I.getOpcode()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000903 case Instruction::Add: Out << " + "; break;
904 case Instruction::Sub: Out << " - "; break;
905 case Instruction::Mul: Out << "*"; break;
906 case Instruction::Div: Out << "/"; break;
907 case Instruction::Rem: Out << "%"; break;
908 case Instruction::And: Out << " & "; break;
909 case Instruction::Or: Out << " | "; break;
910 case Instruction::Xor: Out << " ^ "; break;
911 case Instruction::SetEQ: Out << " == "; break;
912 case Instruction::SetNE: Out << " != "; break;
913 case Instruction::SetLE: Out << " <= "; break;
914 case Instruction::SetGE: Out << " >= "; break;
915 case Instruction::SetLT: Out << " < "; break;
916 case Instruction::SetGT: Out << " > "; break;
917 case Instruction::Shl : Out << " << "; break;
918 case Instruction::Shr : Out << " >> "; break;
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000919 default: std::cerr << "Invalid operator type!" << I; abort();
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000920 }
921
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000922 if (isa<PointerType>(I.getType())) Out << "(long long)";
923 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000924}
925
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000926void CWriter::visitCastInst(CastInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000927 Out << "(";
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000928 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000929 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000930 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000931}
932
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000933void CWriter::visitCallInst(CallInst &I) {
934 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000935 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
936 const Type *RetTy = FTy->getReturnType();
937
Chris Lattnerfabc8802002-08-26 20:50:09 +0000938 writeOperand(I.getOperand(0));
939 Out << "(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000940
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000941 if (I.getNumOperands() > 1) {
942 writeOperand(I.getOperand(1));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000943
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000944 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000945 Out << ", ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000946 writeOperand(I.getOperand(op));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000947 }
948 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000949 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000950}
951
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000952void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000953 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000954 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000955 Out << ")malloc(sizeof(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000956 printType(I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000957 Out << ")";
958
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000959 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000960 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000961 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000962 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000963 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000964}
965
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000966void CWriter::visitAllocaInst(AllocaInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000967 Out << "(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000968 printType(I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000969 Out << ") alloca(sizeof(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000970 printType(I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000971 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000972 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000973 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000974 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000975 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000976 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000977}
978
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000979void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000980 Out << "free(";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000981 writeOperand(I.getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000982 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000983}
984
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000985void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
986 User::op_iterator E) {
987 bool HasImplicitAddress = false;
988 // If accessing a global value with no indexing, avoid *(&GV) syndrome
989 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
990 HasImplicitAddress = true;
991 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
992 HasImplicitAddress = true;
993 Ptr = CPR->getValue(); // Get to the global...
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000994 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000995
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000996 if (I == E) {
997 if (!HasImplicitAddress)
998 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000999
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001000 writeOperandInternal(Ptr);
1001 return;
1002 }
1003
1004 const Constant *CI = dyn_cast<Constant>(I->get());
1005 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1006 Out << "(&";
1007
1008 writeOperandInternal(Ptr);
1009
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001010 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001011 Out << ")";
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001012 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1013 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001014
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001015 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1016 "Can only have implicit address with direct accessing");
1017
1018 if (HasImplicitAddress) {
1019 ++I;
1020 } else if (CI && CI->isNullValue() && I+1 != E) {
1021 // Print out the -> operator if possible...
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001022 if ((*(I+1))->getType() == Type::UByteTy) {
1023 Out << (HasImplicitAddress ? "." : "->");
1024 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1025 I += 2;
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001026 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001027 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001028
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001029 for (; I != E; ++I)
Chris Lattner106ff452002-09-11 01:21:29 +00001030 if ((*I)->getType() == Type::LongTy) {
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001031 Out << "[";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001032 writeOperand(*I);
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001033 Out << "]";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001034 } else {
Chris Lattner59afbf32002-09-12 20:34:47 +00001035 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001036 }
1037}
1038
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001039void CWriter::visitLoadInst(LoadInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001040 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001041 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001042}
1043
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001044void CWriter::visitStoreInst(StoreInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001045 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001046 writeOperand(I.getPointerOperand());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001047 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001048 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001049}
1050
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001051void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001052 Out << "&";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001053 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001054}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001055
1056//===----------------------------------------------------------------------===//
1057// External Interface declaration
1058//===----------------------------------------------------------------------===//
1059
Chris Lattner0e9f93e2002-08-31 00:29:16 +00001060Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }