blob: a34f3f7712505e59ec5ed920ec0b76c1798013f9 [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//
Chris Lattneredd8ce12003-05-03 03:14:35 +00005//===----------------------------------------------------------------------===//
Chris Lattner84e66652003-05-03 07:11:00 +00006
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00007#include "llvm/Assembly/CWriter.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00008#include "llvm/Constants.h"
Chris Lattner2f5f51a2002-05-09 03:28:37 +00009#include "llvm/DerivedTypes.h"
10#include "llvm/Module.h"
Chris Lattnera9f5e052003-04-22 20:19:52 +000011#include "llvm/Instructions.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000012#include "llvm/Pass.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000013#include "llvm/SymbolTable.h"
Chris Lattner18ac3c82003-05-08 18:41:45 +000014#include "llvm/Intrinsics.h"
Chris Lattner0e9f93e2002-08-31 00:29:16 +000015#include "llvm/Analysis/FindUsedTypes.h"
Chris Lattnerd1cf1b42002-09-20 23:26:33 +000016#include "llvm/Analysis/ConstantsScanner.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000017#include "llvm/Support/InstVisitor.h"
Chris Lattner7683a122002-05-09 20:33:35 +000018#include "llvm/Support/InstIterator.h"
Chris Lattner9bda5f52003-06-28 17:53:05 +000019#include "llvm/Support/CallSite.h"
Brian Gaeke49a178b2003-07-25 20:21:06 +000020#include "llvm/Support/Mangler.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000021#include "Support/StringExtras.h"
22#include "Support/STLExtras.h"
Chris Lattner4946a8c2003-10-13 17:13:53 +000023#include "Config/config.h"
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000024#include <algorithm>
Nick Hildenbrandt98502372002-11-18 20:55:50 +000025#include <sstream>
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +000026
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000027namespace {
Chris Lattner0e9f93e2002-08-31 00:29:16 +000028 class CWriter : public Pass, public InstVisitor<CWriter> {
Chris Lattneredd8ce12003-05-03 03:14:35 +000029 std::ostream &Out;
Brian Gaeked9fb37a2003-07-24 20:20:44 +000030 Mangler *Mang;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000031 const Module *TheModule;
Chris Lattneredd8ce12003-05-03 03:14:35 +000032 std::map<const Type *, std::string> TypeNames;
Chris Lattner78771c82002-05-17 04:55:35 +000033 std::set<const Value*> MangledGlobals;
Chris Lattner9bda5f52003-06-28 17:53:05 +000034 bool needsMalloc, emittedInvoke;
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +000035
Chris Lattneredd8ce12003-05-03 03:14:35 +000036 std::map<const ConstantFP *, unsigned> FPConstantMap;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000037 public:
Chris Lattneredd8ce12003-05-03 03:14:35 +000038 CWriter(std::ostream &o) : Out(o) {}
Chris Lattner0e9f93e2002-08-31 00:29:16 +000039
40 void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.setPreservesAll();
42 AU.addRequired<FindUsedTypes>();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000043 }
Chris Lattner0e9f93e2002-08-31 00:29:16 +000044
45 virtual bool run(Module &M) {
46 // Initialize
Chris Lattner0e9f93e2002-08-31 00:29:16 +000047 TheModule = &M;
48
49 // Ensure that all structure types have names...
50 bool Changed = nameAllUsedStructureTypes(M);
Brian Gaeked9fb37a2003-07-24 20:20:44 +000051 Mang = new Mangler(M);
Chris Lattner0e9f93e2002-08-31 00:29:16 +000052
53 // Run...
54 printModule(&M);
55
56 // Free memory...
Brian Gaeked9fb37a2003-07-24 20:20:44 +000057 delete Mang;
Chris Lattner0e9f93e2002-08-31 00:29:16 +000058 TypeNames.clear();
59 MangledGlobals.clear();
60 return false;
61 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000062
Chris Lattneredd8ce12003-05-03 03:14:35 +000063 std::ostream &printType(std::ostream &Out, const Type *Ty,
64 const std::string &VariableName = "",
65 bool IgnoreName = false, bool namedContext = true);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000066
Chris Lattnerbb03efd2002-06-25 15:57:03 +000067 void writeOperand(Value *Operand);
68 void writeOperandInternal(Value *Operand);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000069
Chris Lattner4fbf26d2002-05-09 20:53:56 +000070 private :
Chris Lattner0e9f93e2002-08-31 00:29:16 +000071 bool nameAllUsedStructureTypes(Module &M);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000072 void printModule(Module *M);
Chris Lattner9860e772003-10-12 04:36:29 +000073 void printFloatingPointConstants(Module &M);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +000074 void printSymbolTable(const SymbolTable &ST);
Chris Lattner2c601a72002-09-20 15:05:40 +000075 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
Chris Lattner4cda8352002-08-20 16:55:48 +000076 void printFunctionSignature(const Function *F, bool Prototype);
77
Chris Lattner8c3c4bf2002-05-09 15:49:41 +000078 void printFunction(Function *);
Chris Lattnerb5af06a2002-05-09 03:06:06 +000079
Chris Lattner6d492922002-08-19 21:32:41 +000080 void printConstant(Constant *CPV);
81 void printConstantArray(ConstantArray *CPA);
82
Chris Lattnerd0c668c2002-05-09 21:18:38 +000083 // isInlinableInst - Attempt to inline instructions into their uses to build
84 // trees as much as possible. To do this, we have to consistently decide
85 // what is acceptable to inline, so that variable declarations don't get
86 // printed and an extra copy of the expr is not emitted.
87 //
Chris Lattnerbb03efd2002-06-25 15:57:03 +000088 static bool isInlinableInst(const Instruction &I) {
Chris Lattnerd0c668c2002-05-09 21:18:38 +000089 // Must be an expression, must be used exactly once. If it is dead, we
90 // emit it inline where it would go.
Chris Lattnerfd059242003-10-15 16:48:29 +000091 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
Nick Hildenbrandt2cf2cbc2002-11-06 20:07:54 +000092 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
Chris Lattnerd4e8d312003-07-23 20:45:31 +000093 isa<LoadInst>(I) || isa<VarArgInst>(I))
94 // Don't inline a load across a store or other bad things!
Chris Lattnerd0c668c2002-05-09 21:18:38 +000095 return false;
96
97 // Only inline instruction it it's use is in the same BB as the inst.
Chris Lattnerbb03efd2002-06-25 15:57:03 +000098 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
Chris Lattnerd0c668c2002-05-09 21:18:38 +000099 }
100
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000101 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
102 // variables which are accessed with the & operator. This causes GCC to
103 // generate significantly better code than to emit alloca calls directly.
104 //
105 static const AllocaInst *isDirectAlloca(const Value *V) {
106 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
107 if (!AI) return false;
108 if (AI->isArrayAllocation())
109 return 0; // FIXME: we can also inline fixed size array allocas!
Chris Lattner02a3be02003-09-20 14:39:18 +0000110 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000111 return 0;
112 return AI;
113 }
114
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000115 // Instruction visitation functions
116 friend class InstVisitor<CWriter>;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000117
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000118 void visitReturnInst(ReturnInst &I);
119 void visitBranchInst(BranchInst &I);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000120 void visitSwitchInst(SwitchInst &I);
Chris Lattner9bda5f52003-06-28 17:53:05 +0000121 void visitInvokeInst(InvokeInst &I);
Chris Lattner36143fc2003-09-08 18:54:55 +0000122 void visitUnwindInst(UnwindInst &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000123
Chris Lattner84e66652003-05-03 07:11:00 +0000124 void visitPHINode(PHINode &I);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000125 void visitBinaryOperator(Instruction &I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000126
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000127 void visitCastInst (CastInst &I);
128 void visitCallInst (CallInst &I);
Chris Lattner9bda5f52003-06-28 17:53:05 +0000129 void visitCallSite (CallSite CS);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000130 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000131
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000132 void visitMallocInst(MallocInst &I);
133 void visitAllocaInst(AllocaInst &I);
134 void visitFreeInst (FreeInst &I);
135 void visitLoadInst (LoadInst &I);
136 void visitStoreInst (StoreInst &I);
137 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner18ac3c82003-05-08 18:41:45 +0000138 void visitVarArgInst(VarArgInst &I);
Chris Lattner2f5f51a2002-05-09 03:28:37 +0000139
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000140 void visitInstruction(Instruction &I) {
Chris Lattnere7f65d3b2002-06-30 16:07:20 +0000141 std::cerr << "C Writer does not know about " << I;
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000142 abort();
143 }
144
145 void outputLValue(Instruction *I) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000146 Out << " " << Mang->getValueName(I) << " = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000147 }
148 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
149 unsigned Indent);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000150 void printIndexingExpression(Value *Ptr, User::op_iterator I,
151 User::op_iterator E);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000152 };
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000153}
154
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000155// A pointer type should not use parens around *'s alone, e.g., (**)
Chris Lattneredd8ce12003-05-03 03:14:35 +0000156inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000157 return NameSoFar.find_last_not_of('*') != std::string::npos;
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000158}
159
Chris Lattner83c57752002-08-19 22:17:53 +0000160// Pass the Type* and the variable name and this prints out the variable
161// declaration.
162//
Chris Lattneredd8ce12003-05-03 03:14:35 +0000163std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
164 const std::string &NameSoFar,
165 bool IgnoreName, bool namedContext) {
Chris Lattner83c57752002-08-19 22:17:53 +0000166 if (Ty->isPrimitiveType())
167 switch (Ty->getPrimitiveID()) {
168 case Type::VoidTyID: return Out << "void " << NameSoFar;
169 case Type::BoolTyID: return Out << "bool " << NameSoFar;
170 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
171 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
172 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
173 case Type::ShortTyID: return Out << "short " << NameSoFar;
174 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
175 case Type::IntTyID: return Out << "int " << NameSoFar;
176 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
177 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
178 case Type::FloatTyID: return Out << "float " << NameSoFar;
179 case Type::DoubleTyID: return Out << "double " << NameSoFar;
180 default :
181 std::cerr << "Unknown primitive type: " << Ty << "\n";
182 abort();
183 }
184
185 // Check to see if the type is named.
Chris Lattner04b72c82002-10-16 00:08:22 +0000186 if (!IgnoreName || isa<OpaqueType>(Ty)) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000187 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
Chris Lattner5864da02003-08-24 21:00:22 +0000188 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
Chris Lattner04b72c82002-10-16 00:08:22 +0000189 }
Chris Lattner83c57752002-08-19 22:17:53 +0000190
Chris Lattner83c57752002-08-19 22:17:53 +0000191 switch (Ty->getPrimitiveID()) {
192 case Type::FunctionTyID: {
193 const FunctionType *MTy = cast<FunctionType>(Ty);
Joel Stanley54f60322003-06-25 04:52:09 +0000194 std::stringstream FunctionInnards;
195 FunctionInnards << " (" << NameSoFar << ") (";
Chris Lattner83c57752002-08-19 22:17:53 +0000196 for (FunctionType::ParamTypes::const_iterator
197 I = MTy->getParamTypes().begin(),
198 E = MTy->getParamTypes().end(); I != E; ++I) {
199 if (I != MTy->getParamTypes().begin())
Joel Stanley54f60322003-06-25 04:52:09 +0000200 FunctionInnards << ", ";
201 printType(FunctionInnards, *I, "");
Chris Lattner83c57752002-08-19 22:17:53 +0000202 }
203 if (MTy->isVarArg()) {
204 if (!MTy->getParamTypes().empty())
Joel Stanley54f60322003-06-25 04:52:09 +0000205 FunctionInnards << ", ...";
Chris Lattnerddfc03c2003-05-13 20:15:37 +0000206 } else if (MTy->getParamTypes().empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000207 FunctionInnards << "void";
Chris Lattner83c57752002-08-19 22:17:53 +0000208 }
Joel Stanley54f60322003-06-25 04:52:09 +0000209 FunctionInnards << ")";
210 std::string tstr = FunctionInnards.str();
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000211 printType(Out, MTy->getReturnType(), tstr);
212 return Out;
Chris Lattner83c57752002-08-19 22:17:53 +0000213 }
214 case Type::StructTyID: {
215 const StructType *STy = cast<StructType>(Ty);
216 Out << NameSoFar + " {\n";
217 unsigned Idx = 0;
218 for (StructType::ElementTypes::const_iterator
219 I = STy->getElementTypes().begin(),
220 E = STy->getElementTypes().end(); I != E; ++I) {
221 Out << " ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000222 printType(Out, *I, "field" + utostr(Idx++));
Chris Lattner83c57752002-08-19 22:17:53 +0000223 Out << ";\n";
224 }
225 return Out << "}";
226 }
227
228 case Type::PointerTyID: {
229 const PointerType *PTy = cast<PointerType>(Ty);
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000230 std::string ptrName = "*" + NameSoFar;
231
232 // Do not need parens around "* NameSoFar" if NameSoFar consists only
233 // of zero or more '*' chars *and* this is not an unnamed pointer type
234 // such as the result type in a cast statement. Otherwise, enclose in ( ).
Nick Hildenbrandtc14ded42002-09-23 21:02:50 +0000235 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
236 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000237 ptrName = "(" + ptrName + ")"; //
238
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000239 return printType(Out, PTy->getElementType(), ptrName);
Misha Brukman8f9f9a22003-07-21 16:34:35 +0000240 }
Chris Lattner83c57752002-08-19 22:17:53 +0000241
242 case Type::ArrayTyID: {
243 const ArrayType *ATy = cast<ArrayType>(Ty);
244 unsigned NumElements = ATy->getNumElements();
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000245 return printType(Out, ATy->getElementType(),
Chris Lattner83c57752002-08-19 22:17:53 +0000246 NameSoFar + "[" + utostr(NumElements) + "]");
247 }
Chris Lattner04b72c82002-10-16 00:08:22 +0000248
249 case Type::OpaqueTyID: {
250 static int Count = 0;
Chris Lattneredd8ce12003-05-03 03:14:35 +0000251 std::string TyName = "struct opaque_" + itostr(Count++);
Chris Lattner04b72c82002-10-16 00:08:22 +0000252 assert(TypeNames.find(Ty) == TypeNames.end());
253 TypeNames[Ty] = TyName;
254 return Out << TyName << " " << NameSoFar;
255 }
Chris Lattner83c57752002-08-19 22:17:53 +0000256 default:
257 assert(0 && "Unhandled case in getTypeProps!");
258 abort();
259 }
260
261 return Out;
262}
263
Chris Lattner6d492922002-08-19 21:32:41 +0000264void CWriter::printConstantArray(ConstantArray *CPA) {
265
266 // As a special case, print the array as a string if it is an array of
267 // ubytes or an array of sbytes with positive values.
268 //
269 const Type *ETy = CPA->getType()->getElementType();
270 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
271
272 // Make sure the last character is a null char, as automatically added by C
Chris Lattner02da6c02003-06-16 12:09:09 +0000273 if (isString && (CPA->getNumOperands() == 0 ||
274 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
Chris Lattner6d492922002-08-19 21:32:41 +0000275 isString = false;
276
277 if (isString) {
278 Out << "\"";
Chris Lattner02da6c02003-06-16 12:09:09 +0000279 // Keep track of whether the last number was a hexadecimal escape
280 bool LastWasHex = false;
281
Chris Lattner6d492922002-08-19 21:32:41 +0000282 // Do not include the last character, which we know is null
283 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
Chris Lattnerc07736a2003-07-23 15:22:26 +0000284 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
Chris Lattner6d492922002-08-19 21:32:41 +0000285
Chris Lattner02da6c02003-06-16 12:09:09 +0000286 // Print it out literally if it is a printable character. The only thing
287 // to be careful about is when the last letter output was a hex escape
288 // code, in which case we have to be careful not to print out hex digits
Chris Lattnerda920902003-06-16 12:21:19 +0000289 // explicitly (the C compiler thinks it is a continuation of the previous
290 // character, sheesh...)
Chris Lattner02da6c02003-06-16 12:09:09 +0000291 //
292 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
293 LastWasHex = false;
Nick Hildenbrandt088b4722002-11-06 21:40:23 +0000294 if (C == '"' || C == '\\')
295 Out << "\\" << C;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000296 else
297 Out << C;
Chris Lattner6d492922002-08-19 21:32:41 +0000298 } else {
Chris Lattner02da6c02003-06-16 12:09:09 +0000299 LastWasHex = false;
Chris Lattner6d492922002-08-19 21:32:41 +0000300 switch (C) {
301 case '\n': Out << "\\n"; break;
302 case '\t': Out << "\\t"; break;
303 case '\r': Out << "\\r"; break;
304 case '\v': Out << "\\v"; break;
305 case '\a': Out << "\\a"; break;
Nick Hildenbrandtc3dd2af2002-09-30 21:11:55 +0000306 case '\"': Out << "\\\""; break;
307 case '\'': Out << "\\\'"; break;
Chris Lattner6d492922002-08-19 21:32:41 +0000308 default:
309 Out << "\\x";
Chris Lattner02da6c02003-06-16 12:09:09 +0000310 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
311 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
312 LastWasHex = true;
Chris Lattner6d492922002-08-19 21:32:41 +0000313 break;
314 }
315 }
316 }
317 Out << "\"";
318 } else {
319 Out << "{";
320 if (CPA->getNumOperands()) {
321 Out << " ";
322 printConstant(cast<Constant>(CPA->getOperand(0)));
323 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
324 Out << ", ";
325 printConstant(cast<Constant>(CPA->getOperand(i)));
326 }
327 }
328 Out << " }";
329 }
330}
331
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000332// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
333// textually as a double (rather than as a reference to a stack-allocated
334// variable). We decide this by converting CFP to a string and back into a
335// double, and then checking whether the conversion results in a bit-equal
336// double to the original value of CFP. This depends on us and the target C
337// compiler agreeing on the conversion process (which is pretty likely since we
338// only deal in IEEE FP).
339//
340static bool isFPCSafeToPrint(const ConstantFP *CFP) {
Chris Lattner4946a8c2003-10-13 17:13:53 +0000341#if HAVE_PRINTF_A
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000342 char Buffer[100];
343 sprintf(Buffer, "%a", CFP->getValue());
344
345 if (!strncmp(Buffer, "0x", 2) ||
346 !strncmp(Buffer, "-0x", 3) ||
347 !strncmp(Buffer, "+0x", 3))
348 return atof(Buffer) == CFP->getValue();
349 return false;
350#else
Brian Gaekeb471a232003-06-17 23:55:35 +0000351 std::string StrVal = ftostr(CFP->getValue());
Chris Lattner9860e772003-10-12 04:36:29 +0000352
353 while (StrVal[0] == ' ')
354 StrVal.erase(StrVal.begin());
355
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000356 // Check to make sure that the stringized number is not some string like "Inf"
357 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
Brian Gaekeb471a232003-06-17 23:55:35 +0000358 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
359 ((StrVal[0] == '-' || StrVal[0] == '+') &&
360 (StrVal[1] >= '0' && StrVal[1] <= '9')))
361 // Reparse stringized version!
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000362 return atof(StrVal.c_str()) == CFP->getValue();
Brian Gaekeb471a232003-06-17 23:55:35 +0000363 return false;
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000364#endif
Brian Gaekeb471a232003-06-17 23:55:35 +0000365}
Chris Lattner6d492922002-08-19 21:32:41 +0000366
367// printConstant - The LLVM Constant to C Constant converter.
368void CWriter::printConstant(Constant *CPV) {
369 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
370 switch (CE->getOpcode()) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000371 case Instruction::Cast:
372 Out << "((";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000373 printType(Out, CPV->getType());
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000374 Out << ")";
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000375 printConstant(CE->getOperand(0));
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000376 Out << ")";
377 return;
378
379 case Instruction::GetElementPtr:
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000380 Out << "(&(";
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000381 printIndexingExpression(CE->getOperand(0),
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000382 CPV->op_begin()+1, CPV->op_end());
Nick Hildenbrandtd2eb3862002-10-03 20:47:24 +0000383 Out << "))";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000384 return;
385 case Instruction::Add:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000386 case Instruction::Sub:
Chris Lattner29255922003-08-14 19:19:53 +0000387 case Instruction::Mul:
388 case Instruction::Div:
389 case Instruction::Rem:
390 case Instruction::SetEQ:
391 case Instruction::SetNE:
392 case Instruction::SetLT:
393 case Instruction::SetLE:
394 case Instruction::SetGT:
395 case Instruction::SetGE:
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000396 Out << "(";
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000397 printConstant(CE->getOperand(0));
Chris Lattner29255922003-08-14 19:19:53 +0000398 switch (CE->getOpcode()) {
399 case Instruction::Add: Out << " + "; break;
400 case Instruction::Sub: Out << " - "; break;
401 case Instruction::Mul: Out << " * "; break;
402 case Instruction::Div: Out << " / "; break;
403 case Instruction::Rem: Out << " % "; break;
404 case Instruction::SetEQ: Out << " == "; break;
405 case Instruction::SetNE: Out << " != "; break;
406 case Instruction::SetLT: Out << " < "; break;
407 case Instruction::SetLE: Out << " <= "; break;
408 case Instruction::SetGT: Out << " > "; break;
409 case Instruction::SetGE: Out << " >= "; break;
410 default: assert(0 && "Illegal opcode here!");
411 }
Chris Lattner84c0d5e2003-05-14 17:50:19 +0000412 printConstant(CE->getOperand(1));
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000413 Out << ")";
414 return;
415
Chris Lattner6d492922002-08-19 21:32:41 +0000416 default:
417 std::cerr << "CWriter Error: Unhandled constant expression: "
418 << CE << "\n";
419 abort();
420 }
421 }
422
423 switch (CPV->getType()->getPrimitiveID()) {
424 case Type::BoolTyID:
425 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
426 case Type::SByteTyID:
427 case Type::ShortTyID:
Chris Lattner6d492922002-08-19 21:32:41 +0000428 Out << cast<ConstantSInt>(CPV)->getValue(); break;
Chris Lattner45343ea2003-05-12 15:39:31 +0000429 case Type::IntTyID:
430 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
431 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
432 else
433 Out << cast<ConstantSInt>(CPV)->getValue();
434 break;
435
Chris Lattner6d492922002-08-19 21:32:41 +0000436 case Type::LongTyID:
437 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
438
439 case Type::UByteTyID:
440 case Type::UShortTyID:
441 Out << cast<ConstantUInt>(CPV)->getValue(); break;
442 case Type::UIntTyID:
443 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
444 case Type::ULongTyID:
445 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
446
447 case Type::FloatTyID:
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000448 case Type::DoubleTyID: {
449 ConstantFP *FPC = cast<ConstantFP>(CPV);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000450 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000451 if (I != FPConstantMap.end()) {
452 // Because of FP precision problems we must load from a stack allocated
453 // value that holds the value in hex.
454 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
Chris Lattner9860e772003-10-12 04:36:29 +0000455 << "*)&FPConstant" << I->second << ")";
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000456 } else {
Chris Lattner4946a8c2003-10-13 17:13:53 +0000457#if HAVE_PRINTF_A
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000458 // Print out the constant as a floating point number.
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000459 char Buffer[100];
460 sprintf(Buffer, "%a", FPC->getValue());
461 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
462#else
Chris Lattnerdd76aca2003-10-05 00:40:51 +0000463 Out << ftostr(FPC->getValue());
Chris Lattner5ef6ffd2003-10-12 08:12:58 +0000464#endif
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000465 }
466 break;
467 }
Chris Lattner6d492922002-08-19 21:32:41 +0000468
469 case Type::ArrayTyID:
470 printConstantArray(cast<ConstantArray>(CPV));
471 break;
472
473 case Type::StructTyID: {
474 Out << "{";
475 if (CPV->getNumOperands()) {
476 Out << " ";
477 printConstant(cast<Constant>(CPV->getOperand(0)));
478 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
479 Out << ", ";
480 printConstant(cast<Constant>(CPV->getOperand(i)));
481 }
482 }
483 Out << " }";
484 break;
485 }
486
487 case Type::PointerTyID:
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000488 if (isa<ConstantPointerNull>(CPV)) {
Chris Lattnercf135cb2003-06-02 03:10:53 +0000489 Out << "((";
490 printType(Out, CPV->getType());
491 Out << ")/*NULL*/0)";
Chris Lattner6d492922002-08-19 21:32:41 +0000492 break;
493 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
494 writeOperand(CPR->getValue());
495 break;
496 }
497 // FALL THROUGH
498 default:
499 std::cerr << "Unknown constant type: " << CPV << "\n";
500 abort();
501 }
502}
503
504void CWriter::writeOperandInternal(Value *Operand) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000505 if (Instruction *I = dyn_cast<Instruction>(Operand))
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000506 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +0000507 // Should we inline this instruction to build a tree?
508 Out << "(";
509 visit(*I);
510 Out << ")";
511 return;
512 }
513
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000514 if (Constant *CPV = dyn_cast<Constant>(Operand)) {
Chris Lattner6d492922002-08-19 21:32:41 +0000515 printConstant(CPV);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000516 } else {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000517 Out << Mang->getValueName(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000518 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000519}
520
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000521void CWriter::writeOperand(Value *Operand) {
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000522 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000523 Out << "(&"; // Global variables are references as their addresses by llvm
524
525 writeOperandInternal(Operand);
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000526
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000527 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000528 Out << ")";
529}
530
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000531// nameAllUsedStructureTypes - If there are structure types in the module that
532// are used but do not have names assigned to them in the symbol table yet then
533// we assign them names now.
534//
535bool CWriter::nameAllUsedStructureTypes(Module &M) {
536 // Get a set of types that are used by the program...
537 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
538
539 // Loop over the module symbol table, removing types from UT that are already
540 // named.
541 //
Chris Lattner6e6026b2002-11-20 18:36:02 +0000542 SymbolTable &MST = M.getSymbolTable();
543 if (MST.find(Type::TypeTy) != MST.end())
544 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
545 E = MST.type_end(Type::TypeTy); I != E; ++I)
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000546 UT.erase(cast<Type>(I->second));
547
548 // UT now contains types that are not named. Loop over it, naming structure
549 // types.
550 //
551 bool Changed = false;
552 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
553 I != E; ++I)
554 if (const StructType *ST = dyn_cast<StructType>(*I)) {
Chris Lattner6e6026b2002-11-20 18:36:02 +0000555 ((Value*)ST)->setName("unnamed", &MST);
Chris Lattner0e9f93e2002-08-31 00:29:16 +0000556 Changed = true;
557 }
558 return Changed;
559}
560
Chris Lattner41488192003-06-28 17:15:12 +0000561// generateCompilerSpecificCode - This is where we add conditional compilation
562// directives to cater to specific compilers as need be.
563//
564static void generateCompilerSpecificCode(std::ostream& Out) {
565 // Alloca is hard to get, and we don't want to include stdlib.h here...
566 Out << "/* get a declaration for alloca */\n"
567 << "#ifdef sun\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000568 << "extern void *__builtin_alloca(unsigned long);\n"
569 << "#define alloca(x) __builtin_alloca(x)\n"
570 << "#else\n"
Brian Gaekea0145cc2003-06-16 23:57:13 +0000571 << "#ifndef __FreeBSD__\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000572 << "#include <alloca.h>\n"
Brian Gaekea0145cc2003-06-16 23:57:13 +0000573 << "#endif\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000574 << "#endif\n\n";
Chris Lattner41488192003-06-28 17:15:12 +0000575
576 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
577 // If we aren't being compiled with GCC, just drop these attributes.
Chris Lattner9bda5f52003-06-28 17:53:05 +0000578 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
Chris Lattner41488192003-06-28 17:15:12 +0000579 << "#define __attribute__(X)\n"
580 << "#endif\n";
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000581}
582
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000583void CWriter::printModule(Module *M) {
Chris Lattner78771c82002-05-17 04:55:35 +0000584 // Calculate which global values have names that will collide when we throw
585 // away type information.
Chris Lattner594b9fa2002-05-21 21:10:04 +0000586 { // Scope to delete the FoundNames set when we are done with it...
Chris Lattneredd8ce12003-05-03 03:14:35 +0000587 std::set<std::string> FoundNames;
Chris Lattner78771c82002-05-17 04:55:35 +0000588 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000589 if (I->hasName()) // If the global has a name...
590 if (FoundNames.count(I->getName())) // And the name is already used
591 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000592 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000593 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000594
595 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000596 if (I->hasName()) // If the global has a name...
597 if (FoundNames.count(I->getName())) // And the name is already used
598 MangledGlobals.insert(I); // Mangle the name
Chris Lattner78771c82002-05-17 04:55:35 +0000599 else
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000600 FoundNames.insert(I->getName()); // Otherwise, keep track of name
Chris Lattner78771c82002-05-17 04:55:35 +0000601 }
602
Chris Lattner16c7bb22002-05-09 02:28:59 +0000603 // get declaration for alloca
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000604 Out << "/* Provide Declarations */\n";
Chris Lattner18ac3c82003-05-08 18:41:45 +0000605 Out << "#include <stdarg.h>\n";
Chris Lattnerc436b372003-05-17 22:26:33 +0000606 Out << "#include <setjmp.h>\n";
Chris Lattner41488192003-06-28 17:15:12 +0000607 generateCompilerSpecificCode(Out);
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000608
Chris Lattnercf135cb2003-06-02 03:10:53 +0000609 // Provide a definition for `bool' if not compiling with a C++ compiler.
610 Out << "\n"
Vikram S. Adve969c4ad2002-08-25 20:00:08 +0000611 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000612
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000613 << "\n\n/* Support for floating point constants */\n"
614 << "typedef unsigned long long ConstantDoubleTy;\n"
Chris Lattnereb6f8c72002-11-07 19:43:59 +0000615 << "typedef unsigned int ConstantFloatTy;\n"
Joel Stanleyecd78ac2003-02-12 20:45:00 +0000616
Chris Lattner9bda5f52003-06-28 17:53:05 +0000617 << "\n\n/* Support for the invoke instruction */\n"
618 << "extern struct __llvm_jmpbuf_list_t {\n"
619 << " jmp_buf buf; struct __llvm_jmpbuf_list_t *next;\n"
620 << "} *__llvm_jmpbuf_list;\n"
621
Chris Lattnera4d4a852002-08-19 21:48:40 +0000622 << "\n\n/* Global Declarations */\n";
623
624 // First output all the declarations for the program, because C requires
625 // Functions & globals to be declared before they are used.
626 //
Chris Lattner16c7bb22002-05-09 02:28:59 +0000627
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000628 // Loop over the symbol table, emitting all named constants...
Chris Lattner6e6026b2002-11-20 18:36:02 +0000629 printSymbolTable(M->getSymbolTable());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000630
Chris Lattnera4d4a852002-08-19 21:48:40 +0000631 // Global variable declarations...
632 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000633 Out << "\n/* External Global Variable Declarations */\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000634 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000635 if (I->hasExternalLinkage()) {
636 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000637 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000638 Out << ";\n";
639 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000640 }
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000641 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000642
Chris Lattnera4d4a852002-08-19 21:48:40 +0000643 // Function declarations
644 if (!M->empty()) {
645 Out << "\n/* Function Declarations */\n";
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000646 needsMalloc = true;
Chris Lattner4cda8352002-08-20 16:55:48 +0000647 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Nick Hildenbrandta1a64f82002-11-18 22:21:52 +0000648 // If the function is external and the name collides don't print it.
Chris Lattner18ac3c82003-05-08 18:41:45 +0000649 // Sometimes the bytecode likes to have multiple "declarations" for
Chris Lattneredd8ce12003-05-03 03:14:35 +0000650 // external functions
Chris Lattner18ac3c82003-05-08 18:41:45 +0000651 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
652 !I->getIntrinsicID()) {
Nick Hildenbrandta1a64f82002-11-18 22:21:52 +0000653 printFunctionSignature(I, true);
654 Out << ";\n";
655 }
Chris Lattner4cda8352002-08-20 16:55:48 +0000656 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000657 }
658
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000659 // Print Malloc prototype if needed
Misha Brukmanac25de32003-07-09 17:33:50 +0000660 if (needsMalloc) {
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000661 Out << "\n/* Malloc to make sun happy */\n";
John Criswellcf6d7b02003-07-08 14:52:09 +0000662 Out << "extern void * malloc();\n\n";
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000663 }
664
Joel Stanley54f60322003-06-25 04:52:09 +0000665 // Output the global variable declarations
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000666 if (!M->gempty()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000667 Out << "\n\n/* Global Variable Declarations */\n";
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000668 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
669 if (!I->isExternal()) {
670 Out << "extern ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000671 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Nick Hildenbrandt50de36a2002-10-28 19:05:12 +0000672
673 Out << ";\n";
674 }
675 }
676
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000677 // Output the global variable definitions and contents...
Chris Lattnera4d4a852002-08-19 21:48:40 +0000678 if (!M->gempty()) {
Vikram S. Adve913bfbc2002-09-17 11:50:38 +0000679 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
Chris Lattnere8e035b2002-10-16 20:08:47 +0000680 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
681 if (!I->isExternal()) {
682 if (I->hasInternalLinkage())
683 Out << "static ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000684 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
Chris Lattner76d9f1b2003-06-28 17:08:36 +0000685 if (I->hasLinkOnceLinkage())
686 Out << " __attribute__((common))";
Chris Lattner72ac148d2003-10-16 18:29:00 +0000687 else if (I->hasWeakLinkage())
688 Out << " __attribute__((weak))";
Chris Lattner940b08d2003-06-06 07:10:24 +0000689 if (!I->getInitializer()->isNullValue()) {
690 Out << " = " ;
691 writeOperand(I->getInitializer());
692 }
Chris Lattnere8e035b2002-10-16 20:08:47 +0000693 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000694 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000695 }
696
Chris Lattner9860e772003-10-12 04:36:29 +0000697 // Output all floating point constants that cannot be printed accurately...
698 printFloatingPointConstants(*M);
699
Chris Lattner16c7bb22002-05-09 02:28:59 +0000700 // Output all of the functions...
Chris Lattner9bda5f52003-06-28 17:53:05 +0000701 emittedInvoke = false;
Chris Lattnera4d4a852002-08-19 21:48:40 +0000702 if (!M->empty()) {
703 Out << "\n\n/* Function Bodies */\n";
704 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
705 printFunction(I);
706 }
Chris Lattner9bda5f52003-06-28 17:53:05 +0000707
708 // If the program included an invoke instruction, we need to output the
709 // support code for it here!
710 if (emittedInvoke) {
711 Out << "\n/* More support for the invoke instruction */\n"
712 << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
713 << "__attribute__((common)) = 0;\n";
714 }
Chris Lattner9860e772003-10-12 04:36:29 +0000715
716 // Done with global FP constants
717 FPConstantMap.clear();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000718}
719
Chris Lattner9860e772003-10-12 04:36:29 +0000720/// Output all floating point constants that cannot be printed accurately...
721void CWriter::printFloatingPointConstants(Module &M) {
722 union {
723 double D;
724 unsigned long long U;
725 } DBLUnion;
726
727 union {
728 float F;
729 unsigned U;
730 } FLTUnion;
731
732 // Scan the module for floating point constants. If any FP constant is used
733 // in the function, we want to redirect it here so that we do not depend on
734 // the precision of the printed form, unless the printed form preserves
735 // precision.
736 //
737 unsigned FPCounter = 0;
738 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
739 for (constant_iterator I = constant_begin(F), E = constant_end(F);
740 I != E; ++I)
741 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
742 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
743 !FPConstantMap.count(FPC)) {
744 double Val = FPC->getValue();
745
746 FPConstantMap[FPC] = FPCounter; // Number the FP constants
747
748 if (FPC->getType() == Type::DoubleTy) {
749 DBLUnion.D = Val;
750 Out << "const ConstantDoubleTy FPConstant" << FPCounter++
751 << " = 0x" << std::hex << DBLUnion.U << std::dec
752 << "ULL; /* " << Val << " */\n";
753 } else if (FPC->getType() == Type::FloatTy) {
754 FLTUnion.F = Val;
755 Out << "const ConstantFloatTy FPConstant" << FPCounter++
756 << " = 0x" << std::hex << FLTUnion.U << std::dec
757 << "U; /* " << Val << " */\n";
758 } else
759 assert(0 && "Unknown float type!");
760 }
761
762 Out << "\n";
763 }
764
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000765
Chris Lattner2db41cd2002-09-20 15:12:13 +0000766/// printSymbolTable - Run through symbol table looking for type names. If a
767/// type name is found, emit it's declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000768///
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000769void CWriter::printSymbolTable(const SymbolTable &ST) {
Chris Lattner2db41cd2002-09-20 15:12:13 +0000770 // If there are no type names, exit early.
771 if (ST.find(Type::TypeTy) == ST.end())
772 return;
773
774 // We are only interested in the type plane of the symbol table...
775 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
776 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
777
Chris Lattner58d04d42002-09-20 15:18:30 +0000778 // Print out forward declarations for structure types before anything else!
779 Out << "/* Structure forward decls */\n";
780 for (; I != End; ++I)
781 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000782 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
Chris Lattner58d04d42002-09-20 15:18:30 +0000783 Out << Name << ";\n";
784 TypeNames.insert(std::make_pair(STy, Name));
785 }
786
787 Out << "\n";
788
789 // Now we can print out typedefs...
790 Out << "/* Typedefs */\n";
791 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
792 const Type *Ty = cast<Type>(I->second);
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000793 std::string Name = "l_" + Mangler::makeNameProper(I->first);
Chris Lattner58d04d42002-09-20 15:18:30 +0000794 Out << "typedef ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000795 printType(Out, Ty, Name);
Chris Lattner58d04d42002-09-20 15:18:30 +0000796 Out << ";\n";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000797 }
798
799 Out << "\n";
800
Chris Lattner2c601a72002-09-20 15:05:40 +0000801 // Keep track of which structures have been printed so far...
802 std::set<const StructType *> StructPrinted;
803
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000804 // Loop over all structures then push them into the stack so they are
805 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +0000806 //
Chris Lattner58d04d42002-09-20 15:18:30 +0000807 Out << "/* Structure contents */\n";
Chris Lattner2db41cd2002-09-20 15:12:13 +0000808 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
809 if (const StructType *STy = dyn_cast<StructType>(I->second))
810 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000811}
812
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000813// Push the struct onto the stack and recursively push all structs
814// this one depends on.
Chris Lattner2c601a72002-09-20 15:05:40 +0000815void CWriter::printContainedStructs(const Type *Ty,
816 std::set<const StructType*> &StructPrinted){
Misha Brukmanac25de32003-07-09 17:33:50 +0000817 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000818 //Check to see if we have already printed this struct
Chris Lattner2c601a72002-09-20 15:05:40 +0000819 if (StructPrinted.count(STy) == 0) {
820 // Print all contained types first...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000821 for (StructType::ElementTypes::const_iterator
822 I = STy->getElementTypes().begin(),
823 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner2c601a72002-09-20 15:05:40 +0000824 const Type *Ty1 = I->get();
Chris Lattnera4c047e2002-09-20 14:56:54 +0000825 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattnerab2b3282003-05-29 15:12:27 +0000826 printContainedStructs(*I, StructPrinted);
Chris Lattnera4c047e2002-09-20 14:56:54 +0000827 }
828
Chris Lattner2c601a72002-09-20 15:05:40 +0000829 //Print structure type out..
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000830 StructPrinted.insert(STy);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000831 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000832 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +0000833 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000834 }
Chris Lattnera4c047e2002-09-20 14:56:54 +0000835
Chris Lattner2c601a72002-09-20 15:05:40 +0000836 // If it is an array, check contained types and continue
837 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000838 const Type *Ty1 = ATy->getElementType();
839 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000840 printContainedStructs(Ty1, StructPrinted);
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000841 }
842}
843
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000844
Chris Lattner4cda8352002-08-20 16:55:48 +0000845void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Joel Stanley54f60322003-06-25 04:52:09 +0000846 // If the program provides its own malloc prototype we don't need
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000847 // to include the general one.
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000848 if (Mang->getValueName(F) == "malloc")
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000849 needsMalloc = false;
Joel Stanley54f60322003-06-25 04:52:09 +0000850
851 if (F->hasInternalLinkage()) Out << "static ";
852 if (F->hasLinkOnceLinkage()) Out << "inline ";
853
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000854 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000855 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000856
Joel Stanley54f60322003-06-25 04:52:09 +0000857 std::stringstream FunctionInnards;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000858
859 // Print out the name...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000860 FunctionInnards << Mang->getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000861
Chris Lattner16c7bb22002-05-09 02:28:59 +0000862 if (!F->isExternal()) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000863 if (!F->aempty()) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000864 std::string ArgName;
Chris Lattner4cda8352002-08-20 16:55:48 +0000865 if (F->abegin()->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000866 ArgName = Mang->getValueName(F->abegin());
Joel Stanley54f60322003-06-25 04:52:09 +0000867 printType(FunctionInnards, F->afront().getType(), ArgName);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000868 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
869 I != E; ++I) {
Joel Stanley54f60322003-06-25 04:52:09 +0000870 FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +0000871 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000872 ArgName = Mang->getValueName(I);
Chris Lattner4cda8352002-08-20 16:55:48 +0000873 else
874 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +0000875 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000876 }
877 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000878 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000879 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000880 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000881 FT->getParamTypes().begin(),
882 E = FT->getParamTypes().end(); I != E; ++I) {
Joel Stanley54f60322003-06-25 04:52:09 +0000883 if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
884 printType(FunctionInnards, *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000885 }
886 }
887
Chris Lattner1f8c4a12002-09-20 22:32:30 +0000888 // Finish printing arguments... if this is a vararg function, print the ...,
889 // unless there are no known types, in which case, we just emit ().
890 //
891 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000892 if (FT->getParamTypes().size()) FunctionInnards << ", ";
893 FunctionInnards << "..."; // Output varargs portion of signature!
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000894 }
Joel Stanley54f60322003-06-25 04:52:09 +0000895 FunctionInnards << ")";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000896 // Print out the return type and the entire signature for that matter
Joel Stanley54f60322003-06-25 04:52:09 +0000897 printType(Out, F->getReturnType(), FunctionInnards.str());
Chris Lattner72ac148d2003-10-16 18:29:00 +0000898
899 if (F->hasWeakLinkage()) Out << " __attribute((weak))";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000900}
901
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000902void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000903 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000904
Chris Lattner4cda8352002-08-20 16:55:48 +0000905 printFunctionSignature(F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000906 Out << " {\n";
907
Chris Lattner497e19a2002-05-09 20:39:03 +0000908 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000909 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000910 if (const AllocaInst *AI = isDirectAlloca(*I)) {
911 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000912 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000913 Out << "; /* Address exposed local */\n";
914 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000915 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000916 printType(Out, (*I)->getType(), Mang->getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000917 Out << ";\n";
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000918
Chris Lattner84e66652003-05-03 07:11:00 +0000919 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
920 Out << " ";
Chris Lattner9860e772003-10-12 04:36:29 +0000921 printType(Out, (*I)->getType(),
922 Mang->getValueName(*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +0000923 Out << ";\n";
924 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000925 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000926
927 Out << "\n";
928
Chris Lattner16c7bb22002-05-09 02:28:59 +0000929 // print the basic blocks
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000930 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
931 BasicBlock *Prev = BB->getPrev();
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000932
933 // Don't print the label for the basic block if there are no uses, or if the
Misha Brukman37f92e22003-09-11 22:34:13 +0000934 // only terminator use is the predecessor basic block's terminator. We have
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000935 // to scan the use list because PHI nodes use basic blocks too but do not
936 // require a label to be generated.
937 //
938 bool NeedsLabel = false;
939 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
940 UI != UE; ++UI)
941 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
Chris Lattnerf1acd962003-04-23 19:15:13 +0000942 if (TI != Prev->getTerminator() ||
Chris Lattnerfd045612003-08-28 19:56:10 +0000943 isa<SwitchInst>(Prev->getTerminator()) ||
944 isa<InvokeInst>(Prev->getTerminator())) {
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000945 NeedsLabel = true;
946 break;
947 }
948
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000949 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000950
951 // Output all of the instructions in the basic block...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000952 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000953 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000954 if (II->getType() != Type::VoidTy)
955 outputLValue(II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000956 else
957 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000958 visit(*II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000959 Out << ";\n";
960 }
961 }
962
963 // Don't emit prefix or suffix for the terminator...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000964 visit(*BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000965 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000966
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000967 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000968}
969
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000970// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +0000971// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000972//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000973void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000974 // Don't output a void return if this is the last basic block in the function
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000975 if (I.getNumOperands() == 0 &&
976 &*--I.getParent()->getParent()->end() == I.getParent() &&
977 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000978 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000979 }
Chris Lattner44408262002-05-09 03:50:42 +0000980
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000981 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000982 if (I.getNumOperands()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000983 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000984 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000985 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000986 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000987}
988
Chris Lattnera9f5e052003-04-22 20:19:52 +0000989void CWriter::visitSwitchInst(SwitchInst &SI) {
990 Out << " switch (";
991 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +0000992 Out << ") {\n default:\n";
993 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000994 Out << ";\n";
995 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
996 Out << " case ";
997 writeOperand(SI.getOperand(i));
998 Out << ":\n";
999 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1000 printBranchToBlock(SI.getParent(), Succ, 2);
1001 if (Succ == SI.getParent()->getNext())
1002 Out << " break;\n";
1003 }
1004 Out << " }\n";
1005}
1006
Chris Lattner9bda5f52003-06-28 17:53:05 +00001007void CWriter::visitInvokeInst(InvokeInst &II) {
1008 Out << " {\n"
1009 << " struct __llvm_jmpbuf_list_t Entry;\n"
1010 << " Entry.next = __llvm_jmpbuf_list;\n"
1011 << " if (setjmp(Entry.buf)) {\n"
1012 << " __llvm_jmpbuf_list = Entry.next;\n";
1013 printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
1014 Out << " }\n"
1015 << " __llvm_jmpbuf_list = &Entry;\n"
1016 << " ";
Chris Lattnerfd045612003-08-28 19:56:10 +00001017
1018 if (II.getType() != Type::VoidTy) outputLValue(&II);
Chris Lattner9bda5f52003-06-28 17:53:05 +00001019 visitCallSite(&II);
1020 Out << ";\n"
1021 << " __llvm_jmpbuf_list = Entry.next;\n"
1022 << " }\n";
1023 printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1024 emittedInvoke = true;
1025}
1026
Chris Lattnera9f5e052003-04-22 20:19:52 +00001027
Chris Lattner36143fc2003-09-08 18:54:55 +00001028void CWriter::visitUnwindInst(UnwindInst &I) {
1029 // The unwind instructions causes a control flow transfer out of the current
1030 // function, unwinding the stack until a caller who used the invoke
1031 // instruction is found. In this context, we code generated the invoke
1032 // instruction to add an entry to the top of the jmpbuf_list. Thus, here we
1033 // just have to longjmp to the specified handler.
Chris Lattnerbdbecac2003-09-15 16:47:12 +00001034 Out << " if (__llvm_jmpbuf_list == 0) { /* unwind */\n"
1035 << " extern write();\n"
1036 << " ((void (*)(int, void*, unsigned))write)(2,\n"
1037 << " \"throw found with no handler!\\n\", 31); abort();\n"
Chris Lattner36143fc2003-09-08 18:54:55 +00001038 << " }\n"
1039 << " longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1040 emittedInvoke = true;
1041}
1042
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001043static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001044 // If PHI nodes need copies, we need the copy code...
1045 if (isa<PHINode>(To->front()) ||
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001046 From->getNext() != To) // Not directly successor, need goto
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001047 return true;
1048
1049 // Otherwise we don't need the code.
1050 return false;
1051}
1052
1053void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001054 unsigned Indent) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001055 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner2ee82e02003-04-23 16:36:11 +00001056 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001057 // now we have to do the printing
Chris Lattneredd8ce12003-05-03 03:14:35 +00001058 Out << std::string(Indent, ' ');
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001059 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001060 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1061 Out << "; /* for PHI node */\n";
1062 }
1063
Chris Lattner38756572003-10-13 20:32:04 +00001064 if (CurBB->getNext() != Succ ||
1065 isa<InvokeInst>(CurBB->getTerminator()) ||
1066 isa<SwitchInst>(CurBB->getTerminator())) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001067 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001068 writeOperand(Succ);
1069 Out << ";\n";
1070 }
1071}
1072
Misha Brukman37f92e22003-09-11 22:34:13 +00001073// Branch instruction printing - Avoid printing out a branch to a basic block
1074// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001075//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001076void CWriter::visitBranchInst(BranchInst &I) {
1077 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001078 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001079 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001080 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001081 Out << ") {\n";
1082
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001083 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001084
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001085 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001086 Out << " } else {\n";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001087 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001088 }
1089 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001090 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001091 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001092 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001093 Out << ") {\n";
1094
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001095 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001096 }
1097
1098 Out << " }\n";
1099 } else {
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001100 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001101 }
1102 Out << "\n";
1103}
1104
Chris Lattner84e66652003-05-03 07:11:00 +00001105// PHI nodes get copied into temporary values at the end of predecessor basic
1106// blocks. We now need to copy these temporary values into the REAL value for
1107// the PHI.
1108void CWriter::visitPHINode(PHINode &I) {
1109 writeOperand(&I);
1110 Out << "__PHI_TEMPORARY";
1111}
1112
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001113
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001114void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001115 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001116 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001117
1118 // We must cast the results of binary operations which might be promoted.
1119 bool needsCast = false;
1120 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001121 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1122 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001123 needsCast = true;
1124 Out << "((";
1125 printType(Out, I.getType(), "", false, false);
1126 Out << ")(";
1127 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001128
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001129 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001130
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001131 switch (I.getOpcode()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001132 case Instruction::Add: Out << " + "; break;
1133 case Instruction::Sub: Out << " - "; break;
1134 case Instruction::Mul: Out << "*"; break;
1135 case Instruction::Div: Out << "/"; break;
1136 case Instruction::Rem: Out << "%"; break;
1137 case Instruction::And: Out << " & "; break;
1138 case Instruction::Or: Out << " | "; break;
1139 case Instruction::Xor: Out << " ^ "; break;
1140 case Instruction::SetEQ: Out << " == "; break;
1141 case Instruction::SetNE: Out << " != "; break;
1142 case Instruction::SetLE: Out << " <= "; break;
1143 case Instruction::SetGE: Out << " >= "; break;
1144 case Instruction::SetLT: Out << " < "; break;
1145 case Instruction::SetGT: Out << " > "; break;
1146 case Instruction::Shl : Out << " << "; break;
1147 case Instruction::Shr : Out << " >> "; break;
Chris Lattnere7f65d3b2002-06-30 16:07:20 +00001148 default: std::cerr << "Invalid operator type!" << I; abort();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001149 }
1150
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001151 writeOperand(I.getOperand(1));
Brian Gaeke031a1122003-06-23 20:00:51 +00001152
1153 if (needsCast) {
1154 Out << "))";
1155 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001156}
1157
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001158void CWriter::visitCastInst(CastInst &I) {
Chris Lattnerd13bd222003-06-01 03:36:51 +00001159 if (I.getType() == Type::BoolTy) {
1160 Out << "(";
1161 writeOperand(I.getOperand(0));
1162 Out << " != 0)";
1163 return;
1164 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001165 Out << "(";
Chris Lattneredd8ce12003-05-03 03:14:35 +00001166 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001167 Out << ")";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001168 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1169 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1170 // Avoid "cast to pointer from integer of different size" warnings
1171 Out << "(long)";
1172 }
Chris Lattnerd13bd222003-06-01 03:36:51 +00001173
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001174 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001175}
1176
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001177void CWriter::visitCallInst(CallInst &I) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00001178 // Handle intrinsic function calls first...
1179 if (Function *F = I.getCalledFunction())
1180 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1181 switch (ID) {
1182 default: assert(0 && "Unknown LLVM intrinsic!");
1183 case LLVMIntrinsic::va_start:
Chris Lattner4b2a71d2003-09-10 20:08:00 +00001184 Out << "va_start(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001185 writeOperand(I.getOperand(1));
1186 Out << ", ";
1187 // Output the last argument to the enclosing function...
1188 writeOperand(&I.getParent()->getParent()->aback());
1189 Out << ")";
1190 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00001191 case LLVMIntrinsic::va_end:
Chris Lattner4b2a71d2003-09-10 20:08:00 +00001192 Out << "va_end(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001193 writeOperand(I.getOperand(1));
1194 Out << ")";
1195 return;
1196 case LLVMIntrinsic::va_copy:
Chris Lattner4b2a71d2003-09-10 20:08:00 +00001197 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001198 writeOperand(I.getOperand(1));
1199 Out << ", (va_list)";
1200 writeOperand(I.getOperand(2));
1201 Out << ")";
1202 return;
Chris Lattnere55497c2003-08-24 13:06:10 +00001203
Chris Lattnerc436b372003-05-17 22:26:33 +00001204 case LLVMIntrinsic::setjmp:
Chris Lattner72af6b82003-08-18 16:06:09 +00001205 case LLVMIntrinsic::sigsetjmp:
Misha Brukman37f92e22003-09-11 22:34:13 +00001206 // This intrinsic should never exist in the program, but until we get
Chris Lattner326e40a2003-08-06 18:04:40 +00001207 // setjmp/longjmp transformations going on, we should codegen it to
1208 // something reasonable. This will allow code that never calls longjmp
1209 // to work.
1210 Out << "0";
Chris Lattnerc436b372003-05-17 22:26:33 +00001211 return;
1212 case LLVMIntrinsic::longjmp:
Chris Lattner72af6b82003-08-18 16:06:09 +00001213 case LLVMIntrinsic::siglongjmp:
1214 // Longjmp is not implemented, and never will be. It would cause an
1215 // exception throw.
John Criswell506dad02003-07-31 15:11:08 +00001216 Out << "abort()";
Chris Lattnerc436b372003-05-17 22:26:33 +00001217 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00001218 }
1219 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00001220 visitCallSite(&I);
1221}
Chris Lattner18ac3c82003-05-08 18:41:45 +00001222
Chris Lattner9bda5f52003-06-28 17:53:05 +00001223void CWriter::visitCallSite(CallSite CS) {
1224 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001225 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1226 const Type *RetTy = FTy->getReturnType();
1227
Chris Lattner9bda5f52003-06-28 17:53:05 +00001228 writeOperand(CS.getCalledValue());
Chris Lattnerfabc8802002-08-26 20:50:09 +00001229 Out << "(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001230
Chris Lattner9bda5f52003-06-28 17:53:05 +00001231 if (CS.arg_begin() != CS.arg_end()) {
1232 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1233 writeOperand(*AI);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001234
Chris Lattner9bda5f52003-06-28 17:53:05 +00001235 for (++AI; AI != AE; ++AI) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001236 Out << ", ";
Chris Lattner9bda5f52003-06-28 17:53:05 +00001237 writeOperand(*AI);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001238 }
1239 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001240 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001241}
1242
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001243void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001244 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001245 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001246 Out << ")malloc(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001247 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001248 Out << ")";
1249
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001250 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001251 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001252 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001253 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001254 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001255}
1256
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001257void CWriter::visitAllocaInst(AllocaInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001258 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001259 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001260 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001261 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001262 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001263 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001264 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001265 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001266 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001267 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001268}
1269
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001270void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattner29255922003-08-14 19:19:53 +00001271 Out << "free((char*)";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001272 writeOperand(I.getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001273 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001274}
1275
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001276void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1277 User::op_iterator E) {
1278 bool HasImplicitAddress = false;
1279 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1280 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1281 HasImplicitAddress = true;
1282 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1283 HasImplicitAddress = true;
1284 Ptr = CPR->getValue(); // Get to the global...
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001285 } else if (isDirectAlloca(Ptr)) {
1286 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001287 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001288
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001289 if (I == E) {
1290 if (!HasImplicitAddress)
1291 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001292
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001293 writeOperandInternal(Ptr);
1294 return;
1295 }
1296
Chris Lattnerab2b3282003-05-29 15:12:27 +00001297 const Constant *CI = dyn_cast<Constant>(I);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001298 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1299 Out << "(&";
1300
1301 writeOperandInternal(Ptr);
1302
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001303 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001304 Out << ")";
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001305 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1306 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001307
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001308 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1309 "Can only have implicit address with direct accessing");
1310
1311 if (HasImplicitAddress) {
1312 ++I;
1313 } else if (CI && CI->isNullValue() && I+1 != E) {
1314 // Print out the -> operator if possible...
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001315 if ((*(I+1))->getType() == Type::UByteTy) {
1316 Out << (HasImplicitAddress ? "." : "->");
1317 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1318 I += 2;
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001319 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001320 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001321
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001322 for (; I != E; ++I)
Chris Lattner106ff452002-09-11 01:21:29 +00001323 if ((*I)->getType() == Type::LongTy) {
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001324 Out << "[";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001325 writeOperand(*I);
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001326 Out << "]";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001327 } else {
Chris Lattner59afbf32002-09-12 20:34:47 +00001328 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001329 }
1330}
1331
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001332void CWriter::visitLoadInst(LoadInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001333 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001334 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001335}
1336
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001337void CWriter::visitStoreInst(StoreInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001338 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001339 writeOperand(I.getPointerOperand());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001340 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001341 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001342}
1343
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001344void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001345 Out << "&";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001346 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001347}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001348
Chris Lattner18ac3c82003-05-08 18:41:45 +00001349void CWriter::visitVarArgInst(VarArgInst &I) {
1350 Out << "va_arg((va_list)*";
1351 writeOperand(I.getOperand(0));
1352 Out << ", ";
1353 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1354 Out << ")";
1355}
1356
1357
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001358//===----------------------------------------------------------------------===//
1359// External Interface declaration
1360//===----------------------------------------------------------------------===//
1361
Chris Lattner0e9f93e2002-08-31 00:29:16 +00001362Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }