blob: dea97e92f9086d47e123c019507cc3927022df43 [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 Lattnerbb03efd2002-06-25 15:57:03 +000091 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
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 Lattner940b08d2003-06-06 07:10:24 +0000687 if (!I->getInitializer()->isNullValue()) {
688 Out << " = " ;
689 writeOperand(I->getInitializer());
690 }
Chris Lattnere8e035b2002-10-16 20:08:47 +0000691 Out << ";\n";
Chris Lattnera4d4a852002-08-19 21:48:40 +0000692 }
Chris Lattnera4d4a852002-08-19 21:48:40 +0000693 }
694
Chris Lattner9860e772003-10-12 04:36:29 +0000695 // Output all floating point constants that cannot be printed accurately...
696 printFloatingPointConstants(*M);
697
Chris Lattner16c7bb22002-05-09 02:28:59 +0000698 // Output all of the functions...
Chris Lattner9bda5f52003-06-28 17:53:05 +0000699 emittedInvoke = false;
Chris Lattnera4d4a852002-08-19 21:48:40 +0000700 if (!M->empty()) {
701 Out << "\n\n/* Function Bodies */\n";
702 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
703 printFunction(I);
704 }
Chris Lattner9bda5f52003-06-28 17:53:05 +0000705
706 // If the program included an invoke instruction, we need to output the
707 // support code for it here!
708 if (emittedInvoke) {
709 Out << "\n/* More support for the invoke instruction */\n"
710 << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
711 << "__attribute__((common)) = 0;\n";
712 }
Chris Lattner9860e772003-10-12 04:36:29 +0000713
714 // Done with global FP constants
715 FPConstantMap.clear();
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000716}
717
Chris Lattner9860e772003-10-12 04:36:29 +0000718/// Output all floating point constants that cannot be printed accurately...
719void CWriter::printFloatingPointConstants(Module &M) {
720 union {
721 double D;
722 unsigned long long U;
723 } DBLUnion;
724
725 union {
726 float F;
727 unsigned U;
728 } FLTUnion;
729
730 // Scan the module for floating point constants. If any FP constant is used
731 // in the function, we want to redirect it here so that we do not depend on
732 // the precision of the printed form, unless the printed form preserves
733 // precision.
734 //
735 unsigned FPCounter = 0;
736 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
737 for (constant_iterator I = constant_begin(F), E = constant_end(F);
738 I != E; ++I)
739 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
740 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
741 !FPConstantMap.count(FPC)) {
742 double Val = FPC->getValue();
743
744 FPConstantMap[FPC] = FPCounter; // Number the FP constants
745
746 if (FPC->getType() == Type::DoubleTy) {
747 DBLUnion.D = Val;
748 Out << "const ConstantDoubleTy FPConstant" << FPCounter++
749 << " = 0x" << std::hex << DBLUnion.U << std::dec
750 << "ULL; /* " << Val << " */\n";
751 } else if (FPC->getType() == Type::FloatTy) {
752 FLTUnion.F = Val;
753 Out << "const ConstantFloatTy FPConstant" << FPCounter++
754 << " = 0x" << std::hex << FLTUnion.U << std::dec
755 << "U; /* " << Val << " */\n";
756 } else
757 assert(0 && "Unknown float type!");
758 }
759
760 Out << "\n";
761 }
762
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000763
Chris Lattner2db41cd2002-09-20 15:12:13 +0000764/// printSymbolTable - Run through symbol table looking for type names. If a
765/// type name is found, emit it's declaration...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000766///
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000767void CWriter::printSymbolTable(const SymbolTable &ST) {
Chris Lattner2db41cd2002-09-20 15:12:13 +0000768 // If there are no type names, exit early.
769 if (ST.find(Type::TypeTy) == ST.end())
770 return;
771
772 // We are only interested in the type plane of the symbol table...
773 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
774 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
775
Chris Lattner58d04d42002-09-20 15:18:30 +0000776 // Print out forward declarations for structure types before anything else!
777 Out << "/* Structure forward decls */\n";
778 for (; I != End; ++I)
779 if (const Type *STy = dyn_cast<StructType>(I->second)) {
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000780 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
Chris Lattner58d04d42002-09-20 15:18:30 +0000781 Out << Name << ";\n";
782 TypeNames.insert(std::make_pair(STy, Name));
783 }
784
785 Out << "\n";
786
787 // Now we can print out typedefs...
788 Out << "/* Typedefs */\n";
789 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
790 const Type *Ty = cast<Type>(I->second);
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000791 std::string Name = "l_" + Mangler::makeNameProper(I->first);
Chris Lattner58d04d42002-09-20 15:18:30 +0000792 Out << "typedef ";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000793 printType(Out, Ty, Name);
Chris Lattner58d04d42002-09-20 15:18:30 +0000794 Out << ";\n";
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000795 }
796
797 Out << "\n";
798
Chris Lattner2c601a72002-09-20 15:05:40 +0000799 // Keep track of which structures have been printed so far...
800 std::set<const StructType *> StructPrinted;
801
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000802 // Loop over all structures then push them into the stack so they are
803 // printed in the correct order.
Chris Lattner2db41cd2002-09-20 15:12:13 +0000804 //
Chris Lattner58d04d42002-09-20 15:18:30 +0000805 Out << "/* Structure contents */\n";
Chris Lattner2db41cd2002-09-20 15:12:13 +0000806 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
807 if (const StructType *STy = dyn_cast<StructType>(I->second))
808 printContainedStructs(STy, StructPrinted);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000809}
810
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000811// Push the struct onto the stack and recursively push all structs
812// this one depends on.
Chris Lattner2c601a72002-09-20 15:05:40 +0000813void CWriter::printContainedStructs(const Type *Ty,
814 std::set<const StructType*> &StructPrinted){
Misha Brukmanac25de32003-07-09 17:33:50 +0000815 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000816 //Check to see if we have already printed this struct
Chris Lattner2c601a72002-09-20 15:05:40 +0000817 if (StructPrinted.count(STy) == 0) {
818 // Print all contained types first...
Chris Lattnera4c047e2002-09-20 14:56:54 +0000819 for (StructType::ElementTypes::const_iterator
820 I = STy->getElementTypes().begin(),
821 E = STy->getElementTypes().end(); I != E; ++I) {
Chris Lattner2c601a72002-09-20 15:05:40 +0000822 const Type *Ty1 = I->get();
Chris Lattnera4c047e2002-09-20 14:56:54 +0000823 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattnerab2b3282003-05-29 15:12:27 +0000824 printContainedStructs(*I, StructPrinted);
Chris Lattnera4c047e2002-09-20 14:56:54 +0000825 }
826
Chris Lattner2c601a72002-09-20 15:05:40 +0000827 //Print structure type out..
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000828 StructPrinted.insert(STy);
Chris Lattneredd8ce12003-05-03 03:14:35 +0000829 std::string Name = TypeNames[STy];
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000830 printType(Out, STy, Name, true);
Chris Lattner58d04d42002-09-20 15:18:30 +0000831 Out << ";\n\n";
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000832 }
Chris Lattnera4c047e2002-09-20 14:56:54 +0000833
Chris Lattner2c601a72002-09-20 15:05:40 +0000834 // If it is an array, check contained types and continue
835 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000836 const Type *Ty1 = ATy->getElementType();
837 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
Chris Lattner2c601a72002-09-20 15:05:40 +0000838 printContainedStructs(Ty1, StructPrinted);
Nick Hildenbrandt67aa2e22002-09-14 21:36:24 +0000839 }
840}
841
Chris Lattner3ef6dc72002-05-09 14:40:11 +0000842
Chris Lattner4cda8352002-08-20 16:55:48 +0000843void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
Joel Stanley54f60322003-06-25 04:52:09 +0000844 // If the program provides its own malloc prototype we don't need
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000845 // to include the general one.
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000846 if (Mang->getValueName(F) == "malloc")
Nick Hildenbrandt3cecdc52002-10-23 18:59:40 +0000847 needsMalloc = false;
Joel Stanley54f60322003-06-25 04:52:09 +0000848
849 if (F->hasInternalLinkage()) Out << "static ";
850 if (F->hasLinkOnceLinkage()) Out << "inline ";
851
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000852 // Loop over the arguments, printing them...
Chris Lattner16c7bb22002-05-09 02:28:59 +0000853 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000854
Joel Stanley54f60322003-06-25 04:52:09 +0000855 std::stringstream FunctionInnards;
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000856
857 // Print out the name...
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000858 FunctionInnards << Mang->getValueName(F) << "(";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000859
Chris Lattner16c7bb22002-05-09 02:28:59 +0000860 if (!F->isExternal()) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000861 if (!F->aempty()) {
Chris Lattneredd8ce12003-05-03 03:14:35 +0000862 std::string ArgName;
Chris Lattner4cda8352002-08-20 16:55:48 +0000863 if (F->abegin()->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000864 ArgName = Mang->getValueName(F->abegin());
Joel Stanley54f60322003-06-25 04:52:09 +0000865 printType(FunctionInnards, F->afront().getType(), ArgName);
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000866 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
867 I != E; ++I) {
Joel Stanley54f60322003-06-25 04:52:09 +0000868 FunctionInnards << ", ";
Chris Lattner4cda8352002-08-20 16:55:48 +0000869 if (I->hasName() || !Prototype)
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000870 ArgName = Mang->getValueName(I);
Chris Lattner4cda8352002-08-20 16:55:48 +0000871 else
872 ArgName = "";
Joel Stanley54f60322003-06-25 04:52:09 +0000873 printType(FunctionInnards, I->getType(), ArgName);
Chris Lattnerdeed7a52002-05-09 15:18:52 +0000874 }
875 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000876 } else {
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000877 // Loop over the arguments, printing them...
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000878 for (FunctionType::ParamTypes::const_iterator I =
Chris Lattner16c7bb22002-05-09 02:28:59 +0000879 FT->getParamTypes().begin(),
880 E = FT->getParamTypes().end(); I != E; ++I) {
Joel Stanley54f60322003-06-25 04:52:09 +0000881 if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
882 printType(FunctionInnards, *I);
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000883 }
884 }
885
Chris Lattner1f8c4a12002-09-20 22:32:30 +0000886 // Finish printing arguments... if this is a vararg function, print the ...,
887 // unless there are no known types, in which case, we just emit ().
888 //
889 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
Joel Stanley54f60322003-06-25 04:52:09 +0000890 if (FT->getParamTypes().size()) FunctionInnards << ", ";
891 FunctionInnards << "..."; // Output varargs portion of signature!
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000892 }
Joel Stanley54f60322003-06-25 04:52:09 +0000893 FunctionInnards << ")";
Nick Hildenbrandt98502372002-11-18 20:55:50 +0000894 // Print out the return type and the entire signature for that matter
Joel Stanley54f60322003-06-25 04:52:09 +0000895 printType(Out, F->getReturnType(), FunctionInnards.str());
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000896}
897
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000898void CWriter::printFunction(Function *F) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000899 if (F->isExternal()) return;
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000900
Chris Lattner4cda8352002-08-20 16:55:48 +0000901 printFunctionSignature(F, false);
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000902 Out << " {\n";
903
Chris Lattner497e19a2002-05-09 20:39:03 +0000904 // print local variable information for the function
Chris Lattner7683a122002-05-09 20:33:35 +0000905 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000906 if (const AllocaInst *AI = isDirectAlloca(*I)) {
907 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000908 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000909 Out << "; /* Address exposed local */\n";
910 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
Chris Lattner16c7bb22002-05-09 02:28:59 +0000911 Out << " ";
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000912 printType(Out, (*I)->getType(), Mang->getValueName(*I));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000913 Out << ";\n";
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000914
Chris Lattner84e66652003-05-03 07:11:00 +0000915 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
916 Out << " ";
Chris Lattner9860e772003-10-12 04:36:29 +0000917 printType(Out, (*I)->getType(),
918 Mang->getValueName(*I)+"__PHI_TEMPORARY");
Chris Lattner84e66652003-05-03 07:11:00 +0000919 Out << ";\n";
920 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000921 }
Chris Lattnerd1cf1b42002-09-20 23:26:33 +0000922
923 Out << "\n";
924
Chris Lattner16c7bb22002-05-09 02:28:59 +0000925 // print the basic blocks
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000926 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
927 BasicBlock *Prev = BB->getPrev();
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000928
929 // Don't print the label for the basic block if there are no uses, or if the
Misha Brukman37f92e22003-09-11 22:34:13 +0000930 // only terminator use is the predecessor basic block's terminator. We have
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000931 // to scan the use list because PHI nodes use basic blocks too but do not
932 // require a label to be generated.
933 //
934 bool NeedsLabel = false;
935 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
936 UI != UE; ++UI)
937 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
Chris Lattnerf1acd962003-04-23 19:15:13 +0000938 if (TI != Prev->getTerminator() ||
Chris Lattnerfd045612003-08-28 19:56:10 +0000939 isa<SwitchInst>(Prev->getTerminator()) ||
940 isa<InvokeInst>(Prev->getTerminator())) {
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000941 NeedsLabel = true;
942 break;
943 }
944
Brian Gaeked9fb37a2003-07-24 20:20:44 +0000945 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000946
947 // Output all of the instructions in the basic block...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000948 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
Chris Lattnera8ab89e2003-06-17 04:39:14 +0000949 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000950 if (II->getType() != Type::VoidTy)
951 outputLValue(II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000952 else
953 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000954 visit(*II);
Chris Lattnerd0c668c2002-05-09 21:18:38 +0000955 Out << ";\n";
956 }
957 }
958
959 // Don't emit prefix or suffix for the terminator...
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000960 visit(*BB->getTerminator());
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000961 }
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000962
Chris Lattner8c3c4bf2002-05-09 15:49:41 +0000963 Out << "}\n\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000964}
965
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000966// Specific Instruction type classes... note that all of the casts are
Misha Brukman5560c9d2003-08-18 14:43:39 +0000967// necessary because we use the instruction classes as opaque types...
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000968//
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000969void CWriter::visitReturnInst(ReturnInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000970 // Don't output a void return if this is the last basic block in the function
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000971 if (I.getNumOperands() == 0 &&
972 &*--I.getParent()->getParent()->end() == I.getParent() &&
973 !I.getParent()->size() == 1) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000974 return;
Chris Lattner963b70b2002-05-21 18:05:19 +0000975 }
Chris Lattner44408262002-05-09 03:50:42 +0000976
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000977 Out << " return";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000978 if (I.getNumOperands()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000979 Out << " ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +0000980 writeOperand(I.getOperand(0));
Chris Lattner16c7bb22002-05-09 02:28:59 +0000981 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +0000982 Out << ";\n";
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +0000983}
984
Chris Lattnera9f5e052003-04-22 20:19:52 +0000985void CWriter::visitSwitchInst(SwitchInst &SI) {
986 Out << " switch (";
987 writeOperand(SI.getOperand(0));
Chris Lattnerf1acd962003-04-23 19:15:13 +0000988 Out << ") {\n default:\n";
989 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
Chris Lattnera9f5e052003-04-22 20:19:52 +0000990 Out << ";\n";
991 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
992 Out << " case ";
993 writeOperand(SI.getOperand(i));
994 Out << ":\n";
995 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
996 printBranchToBlock(SI.getParent(), Succ, 2);
997 if (Succ == SI.getParent()->getNext())
998 Out << " break;\n";
999 }
1000 Out << " }\n";
1001}
1002
Chris Lattner9bda5f52003-06-28 17:53:05 +00001003void CWriter::visitInvokeInst(InvokeInst &II) {
1004 Out << " {\n"
1005 << " struct __llvm_jmpbuf_list_t Entry;\n"
1006 << " Entry.next = __llvm_jmpbuf_list;\n"
1007 << " if (setjmp(Entry.buf)) {\n"
1008 << " __llvm_jmpbuf_list = Entry.next;\n";
1009 printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
1010 Out << " }\n"
1011 << " __llvm_jmpbuf_list = &Entry;\n"
1012 << " ";
Chris Lattnerfd045612003-08-28 19:56:10 +00001013
1014 if (II.getType() != Type::VoidTy) outputLValue(&II);
Chris Lattner9bda5f52003-06-28 17:53:05 +00001015 visitCallSite(&II);
1016 Out << ";\n"
1017 << " __llvm_jmpbuf_list = Entry.next;\n"
1018 << " }\n";
1019 printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1020 emittedInvoke = true;
1021}
1022
Chris Lattnera9f5e052003-04-22 20:19:52 +00001023
Chris Lattner36143fc2003-09-08 18:54:55 +00001024void CWriter::visitUnwindInst(UnwindInst &I) {
1025 // The unwind instructions causes a control flow transfer out of the current
1026 // function, unwinding the stack until a caller who used the invoke
1027 // instruction is found. In this context, we code generated the invoke
1028 // instruction to add an entry to the top of the jmpbuf_list. Thus, here we
1029 // just have to longjmp to the specified handler.
Chris Lattnerbdbecac2003-09-15 16:47:12 +00001030 Out << " if (__llvm_jmpbuf_list == 0) { /* unwind */\n"
1031 << " extern write();\n"
1032 << " ((void (*)(int, void*, unsigned))write)(2,\n"
1033 << " \"throw found with no handler!\\n\", 31); abort();\n"
Chris Lattner36143fc2003-09-08 18:54:55 +00001034 << " }\n"
1035 << " longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1036 emittedInvoke = true;
1037}
1038
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001039static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001040 // If PHI nodes need copies, we need the copy code...
1041 if (isa<PHINode>(To->front()) ||
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001042 From->getNext() != To) // Not directly successor, need goto
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001043 return true;
1044
1045 // Otherwise we don't need the code.
1046 return false;
1047}
1048
1049void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
Chris Lattner9bda5f52003-06-28 17:53:05 +00001050 unsigned Indent) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001051 for (BasicBlock::iterator I = Succ->begin();
Chris Lattner2ee82e02003-04-23 16:36:11 +00001052 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001053 // now we have to do the printing
Chris Lattneredd8ce12003-05-03 03:14:35 +00001054 Out << std::string(Indent, ' ');
Brian Gaeked9fb37a2003-07-24 20:20:44 +00001055 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001056 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1057 Out << "; /* for PHI node */\n";
1058 }
1059
Chris Lattnerfd045612003-08-28 19:56:10 +00001060 if (CurBB->getNext() != Succ || isa<InvokeInst>(CurBB->getTerminator())) {
Chris Lattneredd8ce12003-05-03 03:14:35 +00001061 Out << std::string(Indent, ' ') << " goto ";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001062 writeOperand(Succ);
1063 Out << ";\n";
1064 }
1065}
1066
Misha Brukman37f92e22003-09-11 22:34:13 +00001067// Branch instruction printing - Avoid printing out a branch to a basic block
1068// that immediately succeeds the current one.
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001069//
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001070void CWriter::visitBranchInst(BranchInst &I) {
1071 if (I.isConditional()) {
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001072 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001073 Out << " if (";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001074 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001075 Out << ") {\n";
1076
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001077 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001078
Chris Lattner5ef6ffd2003-10-12 08:12:58 +00001079 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001080 Out << " } else {\n";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001081 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001082 }
1083 } else {
Misha Brukman5560c9d2003-08-18 14:43:39 +00001084 // First goto not necessary, assume second one is...
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001085 Out << " if (!";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001086 writeOperand(I.getCondition());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001087 Out << ") {\n";
1088
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001089 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001090 }
1091
1092 Out << " }\n";
1093 } else {
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001094 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001095 }
1096 Out << "\n";
1097}
1098
Chris Lattner84e66652003-05-03 07:11:00 +00001099// PHI nodes get copied into temporary values at the end of predecessor basic
1100// blocks. We now need to copy these temporary values into the REAL value for
1101// the PHI.
1102void CWriter::visitPHINode(PHINode &I) {
1103 writeOperand(&I);
1104 Out << "__PHI_TEMPORARY";
1105}
1106
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001107
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001108void CWriter::visitBinaryOperator(Instruction &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001109 // binary instructions, shift instructions, setCond instructions.
Chris Lattnerf5612b762003-04-23 19:09:22 +00001110 assert(!isa<PointerType>(I.getType()));
Brian Gaeke031a1122003-06-23 20:00:51 +00001111
1112 // We must cast the results of binary operations which might be promoted.
1113 bool needsCast = false;
1114 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
Brian Gaekee99f4cf2003-06-25 03:05:33 +00001115 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1116 || (I.getType() == Type::FloatTy)) {
Brian Gaeke031a1122003-06-23 20:00:51 +00001117 needsCast = true;
1118 Out << "((";
1119 printType(Out, I.getType(), "", false, false);
1120 Out << ")(";
1121 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001122
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001123 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001124
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001125 switch (I.getOpcode()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001126 case Instruction::Add: Out << " + "; break;
1127 case Instruction::Sub: Out << " - "; break;
1128 case Instruction::Mul: Out << "*"; break;
1129 case Instruction::Div: Out << "/"; break;
1130 case Instruction::Rem: Out << "%"; break;
1131 case Instruction::And: Out << " & "; break;
1132 case Instruction::Or: Out << " | "; break;
1133 case Instruction::Xor: Out << " ^ "; break;
1134 case Instruction::SetEQ: Out << " == "; break;
1135 case Instruction::SetNE: Out << " != "; break;
1136 case Instruction::SetLE: Out << " <= "; break;
1137 case Instruction::SetGE: Out << " >= "; break;
1138 case Instruction::SetLT: Out << " < "; break;
1139 case Instruction::SetGT: Out << " > "; break;
1140 case Instruction::Shl : Out << " << "; break;
1141 case Instruction::Shr : Out << " >> "; break;
Chris Lattnere7f65d3b2002-06-30 16:07:20 +00001142 default: std::cerr << "Invalid operator type!" << I; abort();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001143 }
1144
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001145 writeOperand(I.getOperand(1));
Brian Gaeke031a1122003-06-23 20:00:51 +00001146
1147 if (needsCast) {
1148 Out << "))";
1149 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001150}
1151
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001152void CWriter::visitCastInst(CastInst &I) {
Chris Lattnerd13bd222003-06-01 03:36:51 +00001153 if (I.getType() == Type::BoolTy) {
1154 Out << "(";
1155 writeOperand(I.getOperand(0));
1156 Out << " != 0)";
1157 return;
1158 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001159 Out << "(";
Chris Lattneredd8ce12003-05-03 03:14:35 +00001160 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001161 Out << ")";
Chris Lattnerf5612b762003-04-23 19:09:22 +00001162 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1163 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1164 // Avoid "cast to pointer from integer of different size" warnings
1165 Out << "(long)";
1166 }
Chris Lattnerd13bd222003-06-01 03:36:51 +00001167
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001168 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001169}
1170
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001171void CWriter::visitCallInst(CallInst &I) {
Chris Lattner18ac3c82003-05-08 18:41:45 +00001172 // Handle intrinsic function calls first...
1173 if (Function *F = I.getCalledFunction())
1174 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1175 switch (ID) {
1176 default: assert(0 && "Unknown LLVM intrinsic!");
1177 case LLVMIntrinsic::va_start:
Chris Lattner4b2a71d2003-09-10 20:08:00 +00001178 Out << "va_start(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001179 writeOperand(I.getOperand(1));
1180 Out << ", ";
1181 // Output the last argument to the enclosing function...
1182 writeOperand(&I.getParent()->getParent()->aback());
1183 Out << ")";
1184 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00001185 case LLVMIntrinsic::va_end:
Chris Lattner4b2a71d2003-09-10 20:08:00 +00001186 Out << "va_end(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001187 writeOperand(I.getOperand(1));
1188 Out << ")";
1189 return;
1190 case LLVMIntrinsic::va_copy:
Chris Lattner4b2a71d2003-09-10 20:08:00 +00001191 Out << "va_copy(*(va_list*)";
Chris Lattner18ac3c82003-05-08 18:41:45 +00001192 writeOperand(I.getOperand(1));
1193 Out << ", (va_list)";
1194 writeOperand(I.getOperand(2));
1195 Out << ")";
1196 return;
Chris Lattnere55497c2003-08-24 13:06:10 +00001197
Chris Lattnerc436b372003-05-17 22:26:33 +00001198 case LLVMIntrinsic::setjmp:
Chris Lattner72af6b82003-08-18 16:06:09 +00001199 case LLVMIntrinsic::sigsetjmp:
Misha Brukman37f92e22003-09-11 22:34:13 +00001200 // This intrinsic should never exist in the program, but until we get
Chris Lattner326e40a2003-08-06 18:04:40 +00001201 // setjmp/longjmp transformations going on, we should codegen it to
1202 // something reasonable. This will allow code that never calls longjmp
1203 // to work.
1204 Out << "0";
Chris Lattnerc436b372003-05-17 22:26:33 +00001205 return;
1206 case LLVMIntrinsic::longjmp:
Chris Lattner72af6b82003-08-18 16:06:09 +00001207 case LLVMIntrinsic::siglongjmp:
1208 // Longjmp is not implemented, and never will be. It would cause an
1209 // exception throw.
John Criswell506dad02003-07-31 15:11:08 +00001210 Out << "abort()";
Chris Lattnerc436b372003-05-17 22:26:33 +00001211 return;
Chris Lattner18ac3c82003-05-08 18:41:45 +00001212 }
1213 }
Chris Lattner9bda5f52003-06-28 17:53:05 +00001214 visitCallSite(&I);
1215}
Chris Lattner18ac3c82003-05-08 18:41:45 +00001216
Chris Lattner9bda5f52003-06-28 17:53:05 +00001217void CWriter::visitCallSite(CallSite CS) {
1218 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001219 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1220 const Type *RetTy = FTy->getReturnType();
1221
Chris Lattner9bda5f52003-06-28 17:53:05 +00001222 writeOperand(CS.getCalledValue());
Chris Lattnerfabc8802002-08-26 20:50:09 +00001223 Out << "(";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001224
Chris Lattner9bda5f52003-06-28 17:53:05 +00001225 if (CS.arg_begin() != CS.arg_end()) {
1226 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1227 writeOperand(*AI);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001228
Chris Lattner9bda5f52003-06-28 17:53:05 +00001229 for (++AI; AI != AE; ++AI) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001230 Out << ", ";
Chris Lattner9bda5f52003-06-28 17:53:05 +00001231 writeOperand(*AI);
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001232 }
1233 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001234 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001235}
1236
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001237void CWriter::visitMallocInst(MallocInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001238 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001239 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001240 Out << ")malloc(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001241 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001242 Out << ")";
1243
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001244 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001245 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001246 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001247 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001248 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001249}
1250
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001251void CWriter::visitAllocaInst(AllocaInst &I) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001252 Out << "(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001253 printType(Out, I.getType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001254 Out << ") alloca(sizeof(";
Nick Hildenbrandt98502372002-11-18 20:55:50 +00001255 printType(Out, I.getType()->getElementType());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001256 Out << ")";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001257 if (I.isArrayAllocation()) {
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001258 Out << " * " ;
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001259 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001260 }
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001261 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001262}
1263
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001264void CWriter::visitFreeInst(FreeInst &I) {
Chris Lattner29255922003-08-14 19:19:53 +00001265 Out << "free((char*)";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001266 writeOperand(I.getOperand(0));
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001267 Out << ")";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001268}
1269
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001270void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1271 User::op_iterator E) {
1272 bool HasImplicitAddress = false;
1273 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1274 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1275 HasImplicitAddress = true;
1276 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1277 HasImplicitAddress = true;
1278 Ptr = CPR->getValue(); // Get to the global...
Chris Lattnera8ab89e2003-06-17 04:39:14 +00001279 } else if (isDirectAlloca(Ptr)) {
1280 HasImplicitAddress = true;
Chris Lattnerd0c668c2002-05-09 21:18:38 +00001281 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001282
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001283 if (I == E) {
1284 if (!HasImplicitAddress)
1285 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001286
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001287 writeOperandInternal(Ptr);
1288 return;
1289 }
1290
Chris Lattnerab2b3282003-05-29 15:12:27 +00001291 const Constant *CI = dyn_cast<Constant>(I);
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001292 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1293 Out << "(&";
1294
1295 writeOperandInternal(Ptr);
1296
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001297 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001298 Out << ")";
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001299 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1300 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001301
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001302 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1303 "Can only have implicit address with direct accessing");
1304
1305 if (HasImplicitAddress) {
1306 ++I;
1307 } else if (CI && CI->isNullValue() && I+1 != E) {
1308 // Print out the -> operator if possible...
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001309 if ((*(I+1))->getType() == Type::UByteTy) {
1310 Out << (HasImplicitAddress ? "." : "->");
1311 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1312 I += 2;
Nick Hildenbrandte548f002002-09-25 20:29:26 +00001313 }
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001314 }
Chris Lattner5dfe7672002-08-22 22:48:55 +00001315
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001316 for (; I != E; ++I)
Chris Lattner106ff452002-09-11 01:21:29 +00001317 if ((*I)->getType() == Type::LongTy) {
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001318 Out << "[";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001319 writeOperand(*I);
Vikram S. Adve9d6f13f2002-09-15 21:51:04 +00001320 Out << "]";
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001321 } else {
Chris Lattner59afbf32002-09-12 20:34:47 +00001322 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001323 }
1324}
1325
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001326void CWriter::visitLoadInst(LoadInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001327 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001328 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001329}
1330
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001331void CWriter::visitStoreInst(StoreInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001332 Out << "*";
Chris Lattner5dfe7672002-08-22 22:48:55 +00001333 writeOperand(I.getPointerOperand());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001334 Out << " = ";
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001335 writeOperand(I.getOperand(0));
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001336}
1337
Chris Lattnerbb03efd2002-06-25 15:57:03 +00001338void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
Nick Hildenbrandtca626922002-10-02 21:14:33 +00001339 Out << "&";
Chris Lattnerdf35a1c2002-08-19 23:09:46 +00001340 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
Chris Lattner4fbf26d2002-05-09 20:53:56 +00001341}
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001342
Chris Lattner18ac3c82003-05-08 18:41:45 +00001343void CWriter::visitVarArgInst(VarArgInst &I) {
1344 Out << "va_arg((va_list)*";
1345 writeOperand(I.getOperand(0));
1346 Out << ", ";
1347 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1348 Out << ")";
1349}
1350
1351
Sumant Kowshik9ddc86c2002-05-08 18:09:58 +00001352//===----------------------------------------------------------------------===//
1353// External Interface declaration
1354//===----------------------------------------------------------------------===//
1355
Chris Lattner0e9f93e2002-08-31 00:29:16 +00001356Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }