1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library converts LLVM code to C code, compilable by GCC.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Assembly/CWriter.h"
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/Module.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/Pass.h"
13 #include "llvm/SymbolTable.h"
14 #include "llvm/Intrinsics.h"
15 #include "llvm/Analysis/FindUsedTypes.h"
16 #include "llvm/Analysis/ConstantsScanner.h"
17 #include "llvm/Support/InstVisitor.h"
18 #include "llvm/Support/InstIterator.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/Mangler.h"
21 #include "Support/StringExtras.h"
22 #include "Support/STLExtras.h"
23 #include "Config/config.h"
28 class CWriter : public Pass, public InstVisitor<CWriter> {
31 const Module *TheModule;
32 std::map<const Type *, std::string> TypeNames;
33 std::set<const Value*> MangledGlobals;
34 bool needsMalloc, emittedInvoke;
36 std::map<const ConstantFP *, unsigned> FPConstantMap;
38 CWriter(std::ostream &o) : Out(o) {}
40 void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<FindUsedTypes>();
45 virtual bool run(Module &M) {
49 // Ensure that all structure types have names...
50 bool Changed = nameAllUsedStructureTypes(M);
51 Mang = new Mangler(M);
59 MangledGlobals.clear();
63 std::ostream &printType(std::ostream &Out, const Type *Ty,
64 const std::string &VariableName = "",
65 bool IgnoreName = false, bool namedContext = true);
67 void writeOperand(Value *Operand);
68 void writeOperandInternal(Value *Operand);
71 bool nameAllUsedStructureTypes(Module &M);
72 void printModule(Module *M);
73 void printFloatingPointConstants(Module &M);
74 void printSymbolTable(const SymbolTable &ST);
75 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
76 void printFunctionSignature(const Function *F, bool Prototype);
78 void printFunction(Function *);
80 void printConstant(Constant *CPV);
81 void printConstantArray(ConstantArray *CPA);
83 // 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.
88 static bool isInlinableInst(const Instruction &I) {
89 // Must be an expression, must be used exactly once. If it is dead, we
90 // emit it inline where it would go.
91 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
92 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
93 isa<LoadInst>(I) || isa<VarArgInst>(I))
94 // Don't inline a load across a store or other bad things!
97 // Only inline instruction it it's use is in the same BB as the inst.
98 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
101 // 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.
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!
110 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
115 // Instruction visitation functions
116 friend class InstVisitor<CWriter>;
118 void visitReturnInst(ReturnInst &I);
119 void visitBranchInst(BranchInst &I);
120 void visitSwitchInst(SwitchInst &I);
121 void visitInvokeInst(InvokeInst &I);
122 void visitUnwindInst(UnwindInst &I);
124 void visitPHINode(PHINode &I);
125 void visitBinaryOperator(Instruction &I);
127 void visitCastInst (CastInst &I);
128 void visitCallInst (CallInst &I);
129 void visitCallSite (CallSite CS);
130 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
132 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);
138 void visitVarArgInst(VarArgInst &I);
140 void visitInstruction(Instruction &I) {
141 std::cerr << "C Writer does not know about " << I;
145 void outputLValue(Instruction *I) {
146 Out << " " << Mang->getValueName(I) << " = ";
148 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
150 void printIndexingExpression(Value *Ptr, User::op_iterator I,
151 User::op_iterator E);
155 // A pointer type should not use parens around *'s alone, e.g., (**)
156 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
157 return NameSoFar.find_last_not_of('*') != std::string::npos;
160 // Pass the Type* and the variable name and this prints out the variable
163 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
164 const std::string &NameSoFar,
165 bool IgnoreName, bool namedContext) {
166 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;
181 std::cerr << "Unknown primitive type: " << Ty << "\n";
185 // Check to see if the type is named.
186 if (!IgnoreName || isa<OpaqueType>(Ty)) {
187 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
188 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
191 switch (Ty->getPrimitiveID()) {
192 case Type::FunctionTyID: {
193 const FunctionType *MTy = cast<FunctionType>(Ty);
194 std::stringstream FunctionInnards;
195 FunctionInnards << " (" << NameSoFar << ") (";
196 for (FunctionType::ParamTypes::const_iterator
197 I = MTy->getParamTypes().begin(),
198 E = MTy->getParamTypes().end(); I != E; ++I) {
199 if (I != MTy->getParamTypes().begin())
200 FunctionInnards << ", ";
201 printType(FunctionInnards, *I, "");
203 if (MTy->isVarArg()) {
204 if (!MTy->getParamTypes().empty())
205 FunctionInnards << ", ...";
206 } else if (MTy->getParamTypes().empty()) {
207 FunctionInnards << "void";
209 FunctionInnards << ")";
210 std::string tstr = FunctionInnards.str();
211 printType(Out, MTy->getReturnType(), tstr);
214 case Type::StructTyID: {
215 const StructType *STy = cast<StructType>(Ty);
216 Out << NameSoFar + " {\n";
218 for (StructType::ElementTypes::const_iterator
219 I = STy->getElementTypes().begin(),
220 E = STy->getElementTypes().end(); I != E; ++I) {
222 printType(Out, *I, "field" + utostr(Idx++));
228 case Type::PointerTyID: {
229 const PointerType *PTy = cast<PointerType>(Ty);
230 std::string ptrName = "*" + NameSoFar;
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 ( ).
235 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
236 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
237 ptrName = "(" + ptrName + ")"; //
239 return printType(Out, PTy->getElementType(), ptrName);
242 case Type::ArrayTyID: {
243 const ArrayType *ATy = cast<ArrayType>(Ty);
244 unsigned NumElements = ATy->getNumElements();
245 return printType(Out, ATy->getElementType(),
246 NameSoFar + "[" + utostr(NumElements) + "]");
249 case Type::OpaqueTyID: {
250 static int Count = 0;
251 std::string TyName = "struct opaque_" + itostr(Count++);
252 assert(TypeNames.find(Ty) == TypeNames.end());
253 TypeNames[Ty] = TyName;
254 return Out << TyName << " " << NameSoFar;
257 assert(0 && "Unhandled case in getTypeProps!");
264 void CWriter::printConstantArray(ConstantArray *CPA) {
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.
269 const Type *ETy = CPA->getType()->getElementType();
270 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
272 // Make sure the last character is a null char, as automatically added by C
273 if (isString && (CPA->getNumOperands() == 0 ||
274 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
279 // Keep track of whether the last number was a hexadecimal escape
280 bool LastWasHex = false;
282 // Do not include the last character, which we know is null
283 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
284 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
286 // 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
289 // explicitly (the C compiler thinks it is a continuation of the previous
290 // character, sheesh...)
292 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
294 if (C == '"' || 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;
306 case '\"': Out << "\\\""; break;
307 case '\'': Out << "\\\'"; break;
310 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'));
320 if (CPA->getNumOperands()) {
322 printConstant(cast<Constant>(CPA->getOperand(0)));
323 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
325 printConstant(cast<Constant>(CPA->getOperand(i)));
332 // 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).
340 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
343 sprintf(Buffer, "%a", CFP->getValue());
345 if (!strncmp(Buffer, "0x", 2) ||
346 !strncmp(Buffer, "-0x", 3) ||
347 !strncmp(Buffer, "+0x", 3))
348 return atof(Buffer) == CFP->getValue();
351 std::string StrVal = ftostr(CFP->getValue());
353 while (StrVal[0] == ' ')
354 StrVal.erase(StrVal.begin());
356 // 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.
358 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
359 ((StrVal[0] == '-' || StrVal[0] == '+') &&
360 (StrVal[1] >= '0' && StrVal[1] <= '9')))
361 // Reparse stringized version!
362 return atof(StrVal.c_str()) == CFP->getValue();
367 // printConstant - The LLVM Constant to C Constant converter.
368 void CWriter::printConstant(Constant *CPV) {
369 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
370 switch (CE->getOpcode()) {
371 case Instruction::Cast:
373 printType(Out, CPV->getType());
375 printConstant(CE->getOperand(0));
379 case Instruction::GetElementPtr:
381 printIndexingExpression(CE->getOperand(0),
382 CPV->op_begin()+1, CPV->op_end());
385 case Instruction::Add:
386 case Instruction::Sub:
387 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:
397 printConstant(CE->getOperand(0));
398 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!");
412 printConstant(CE->getOperand(1));
417 std::cerr << "CWriter Error: Unhandled constant expression: "
423 switch (CPV->getType()->getPrimitiveID()) {
425 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
426 case Type::SByteTyID:
427 case Type::ShortTyID:
428 Out << cast<ConstantSInt>(CPV)->getValue(); break;
430 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
431 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
433 Out << cast<ConstantSInt>(CPV)->getValue();
437 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
439 case Type::UByteTyID:
440 case Type::UShortTyID:
441 Out << cast<ConstantUInt>(CPV)->getValue(); break;
443 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
444 case Type::ULongTyID:
445 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
447 case Type::FloatTyID:
448 case Type::DoubleTyID: {
449 ConstantFP *FPC = cast<ConstantFP>(CPV);
450 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
451 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")
455 << "*)&FPConstant" << I->second << ")";
458 // Print out the constant as a floating point number.
460 sprintf(Buffer, "%a", FPC->getValue());
461 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
463 Out << ftostr(FPC->getValue());
469 case Type::ArrayTyID:
470 printConstantArray(cast<ConstantArray>(CPV));
473 case Type::StructTyID: {
475 if (CPV->getNumOperands()) {
477 printConstant(cast<Constant>(CPV->getOperand(0)));
478 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
480 printConstant(cast<Constant>(CPV->getOperand(i)));
487 case Type::PointerTyID:
488 if (isa<ConstantPointerNull>(CPV)) {
490 printType(Out, CPV->getType());
491 Out << ")/*NULL*/0)";
493 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
494 writeOperand(CPR->getValue());
499 std::cerr << "Unknown constant type: " << CPV << "\n";
504 void CWriter::writeOperandInternal(Value *Operand) {
505 if (Instruction *I = dyn_cast<Instruction>(Operand))
506 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
507 // Should we inline this instruction to build a tree?
514 if (Constant *CPV = dyn_cast<Constant>(Operand)) {
517 Out << Mang->getValueName(Operand);
521 void CWriter::writeOperand(Value *Operand) {
522 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
523 Out << "(&"; // Global variables are references as their addresses by llvm
525 writeOperandInternal(Operand);
527 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
531 // 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.
535 bool 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();
539 // Loop over the module symbol table, removing types from UT that are already
542 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)
546 UT.erase(cast<Type>(I->second));
548 // UT now contains types that are not named. Loop over it, naming structure
551 bool Changed = false;
552 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
554 if (const StructType *ST = dyn_cast<StructType>(*I)) {
555 ((Value*)ST)->setName("unnamed", &MST);
561 // generateCompilerSpecificCode - This is where we add conditional compilation
562 // directives to cater to specific compilers as need be.
564 static 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"
568 << "extern void *__builtin_alloca(unsigned long);\n"
569 << "#define alloca(x) __builtin_alloca(x)\n"
571 << "#ifndef __FreeBSD__\n"
572 << "#include <alloca.h>\n"
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.
578 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
579 << "#define __attribute__(X)\n"
583 void CWriter::printModule(Module *M) {
584 // Calculate which global values have names that will collide when we throw
585 // away type information.
586 { // Scope to delete the FoundNames set when we are done with it...
587 std::set<std::string> FoundNames;
588 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
589 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
593 FoundNames.insert(I->getName()); // Otherwise, keep track of name
595 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
596 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
600 FoundNames.insert(I->getName()); // Otherwise, keep track of name
603 // get declaration for alloca
604 Out << "/* Provide Declarations */\n";
605 Out << "#include <stdarg.h>\n";
606 Out << "#include <setjmp.h>\n";
607 generateCompilerSpecificCode(Out);
609 // Provide a definition for `bool' if not compiling with a C++ compiler.
611 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
613 << "\n\n/* Support for floating point constants */\n"
614 << "typedef unsigned long long ConstantDoubleTy;\n"
615 << "typedef unsigned int ConstantFloatTy;\n"
617 << "\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"
622 << "\n\n/* Global Declarations */\n";
624 // First output all the declarations for the program, because C requires
625 // Functions & globals to be declared before they are used.
628 // Loop over the symbol table, emitting all named constants...
629 printSymbolTable(M->getSymbolTable());
631 // Global variable declarations...
633 Out << "\n/* External Global Variable Declarations */\n";
634 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
635 if (I->hasExternalLinkage()) {
637 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
643 // Function declarations
645 Out << "\n/* Function Declarations */\n";
647 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
648 // If the function is external and the name collides don't print it.
649 // Sometimes the bytecode likes to have multiple "declarations" for
650 // external functions
651 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
652 !I->getIntrinsicID()) {
653 printFunctionSignature(I, true);
659 // Print Malloc prototype if needed
661 Out << "\n/* Malloc to make sun happy */\n";
662 Out << "extern void * malloc();\n\n";
665 // Output the global variable declarations
667 Out << "\n\n/* Global Variable Declarations */\n";
668 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
669 if (!I->isExternal()) {
671 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
677 // Output the global variable definitions and contents...
679 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
680 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
681 if (!I->isExternal()) {
682 if (I->hasInternalLinkage())
684 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
685 if (I->hasLinkOnceLinkage())
686 Out << " __attribute__((common))";
687 if (!I->getInitializer()->isNullValue()) {
689 writeOperand(I->getInitializer());
695 // Output all floating point constants that cannot be printed accurately...
696 printFloatingPointConstants(*M);
698 // Output all of the functions...
699 emittedInvoke = false;
701 Out << "\n\n/* Function Bodies */\n";
702 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
706 // If the program included an invoke instruction, we need to output the
707 // support code for it here!
709 Out << "\n/* More support for the invoke instruction */\n"
710 << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
711 << "__attribute__((common)) = 0;\n";
714 // Done with global FP constants
715 FPConstantMap.clear();
718 /// Output all floating point constants that cannot be printed accurately...
719 void CWriter::printFloatingPointConstants(Module &M) {
722 unsigned long long U;
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
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);
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();
744 FPConstantMap[FPC] = FPCounter; // Number the FP constants
746 if (FPC->getType() == Type::DoubleTy) {
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) {
753 Out << "const ConstantFloatTy FPConstant" << FPCounter++
754 << " = 0x" << std::hex << FLTUnion.U << std::dec
755 << "U; /* " << Val << " */\n";
757 assert(0 && "Unknown float type!");
764 /// printSymbolTable - Run through symbol table looking for type names. If a
765 /// type name is found, emit it's declaration...
767 void CWriter::printSymbolTable(const SymbolTable &ST) {
768 // If there are no type names, exit early.
769 if (ST.find(Type::TypeTy) == ST.end())
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);
776 // 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)) {
780 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
781 Out << Name << ";\n";
782 TypeNames.insert(std::make_pair(STy, Name));
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);
791 std::string Name = "l_" + Mangler::makeNameProper(I->first);
793 printType(Out, Ty, Name);
799 // Keep track of which structures have been printed so far...
800 std::set<const StructType *> StructPrinted;
802 // Loop over all structures then push them into the stack so they are
803 // printed in the correct order.
805 Out << "/* Structure contents */\n";
806 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
807 if (const StructType *STy = dyn_cast<StructType>(I->second))
808 printContainedStructs(STy, StructPrinted);
811 // Push the struct onto the stack and recursively push all structs
812 // this one depends on.
813 void CWriter::printContainedStructs(const Type *Ty,
814 std::set<const StructType*> &StructPrinted){
815 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
816 //Check to see if we have already printed this struct
817 if (StructPrinted.count(STy) == 0) {
818 // Print all contained types first...
819 for (StructType::ElementTypes::const_iterator
820 I = STy->getElementTypes().begin(),
821 E = STy->getElementTypes().end(); I != E; ++I) {
822 const Type *Ty1 = I->get();
823 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
824 printContainedStructs(*I, StructPrinted);
827 //Print structure type out..
828 StructPrinted.insert(STy);
829 std::string Name = TypeNames[STy];
830 printType(Out, STy, Name, true);
834 // If it is an array, check contained types and continue
835 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
836 const Type *Ty1 = ATy->getElementType();
837 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
838 printContainedStructs(Ty1, StructPrinted);
843 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
844 // If the program provides its own malloc prototype we don't need
845 // to include the general one.
846 if (Mang->getValueName(F) == "malloc")
849 if (F->hasInternalLinkage()) Out << "static ";
850 if (F->hasLinkOnceLinkage()) Out << "inline ";
852 // Loop over the arguments, printing them...
853 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
855 std::stringstream FunctionInnards;
857 // Print out the name...
858 FunctionInnards << Mang->getValueName(F) << "(";
860 if (!F->isExternal()) {
863 if (F->abegin()->hasName() || !Prototype)
864 ArgName = Mang->getValueName(F->abegin());
865 printType(FunctionInnards, F->afront().getType(), ArgName);
866 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
868 FunctionInnards << ", ";
869 if (I->hasName() || !Prototype)
870 ArgName = Mang->getValueName(I);
873 printType(FunctionInnards, I->getType(), ArgName);
877 // Loop over the arguments, printing them...
878 for (FunctionType::ParamTypes::const_iterator I =
879 FT->getParamTypes().begin(),
880 E = FT->getParamTypes().end(); I != E; ++I) {
881 if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
882 printType(FunctionInnards, *I);
886 // Finish printing arguments... if this is a vararg function, print the ...,
887 // unless there are no known types, in which case, we just emit ().
889 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
890 if (FT->getParamTypes().size()) FunctionInnards << ", ";
891 FunctionInnards << "..."; // Output varargs portion of signature!
893 FunctionInnards << ")";
894 // Print out the return type and the entire signature for that matter
895 printType(Out, F->getReturnType(), FunctionInnards.str());
898 void CWriter::printFunction(Function *F) {
899 if (F->isExternal()) return;
901 printFunctionSignature(F, false);
904 // print local variable information for the function
905 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
906 if (const AllocaInst *AI = isDirectAlloca(*I)) {
908 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
909 Out << "; /* Address exposed local */\n";
910 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
912 printType(Out, (*I)->getType(), Mang->getValueName(*I));
915 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
917 printType(Out, (*I)->getType(),
918 Mang->getValueName(*I)+"__PHI_TEMPORARY");
925 // print the basic blocks
926 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
927 BasicBlock *Prev = BB->getPrev();
929 // Don't print the label for the basic block if there are no uses, or if the
930 // only terminator use is the predecessor basic block's terminator. We have
931 // to scan the use list because PHI nodes use basic blocks too but do not
932 // require a label to be generated.
934 bool NeedsLabel = false;
935 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
937 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
938 if (TI != Prev->getTerminator() ||
939 isa<SwitchInst>(Prev->getTerminator()) ||
940 isa<InvokeInst>(Prev->getTerminator())) {
945 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
947 // Output all of the instructions in the basic block...
948 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
949 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
950 if (II->getType() != Type::VoidTy)
959 // Don't emit prefix or suffix for the terminator...
960 visit(*BB->getTerminator());
966 // Specific Instruction type classes... note that all of the casts are
967 // necessary because we use the instruction classes as opaque types...
969 void CWriter::visitReturnInst(ReturnInst &I) {
970 // Don't output a void return if this is the last basic block in the function
971 if (I.getNumOperands() == 0 &&
972 &*--I.getParent()->getParent()->end() == I.getParent() &&
973 !I.getParent()->size() == 1) {
978 if (I.getNumOperands()) {
980 writeOperand(I.getOperand(0));
985 void CWriter::visitSwitchInst(SwitchInst &SI) {
987 writeOperand(SI.getOperand(0));
988 Out << ") {\n default:\n";
989 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
991 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
993 writeOperand(SI.getOperand(i));
995 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
996 printBranchToBlock(SI.getParent(), Succ, 2);
997 if (Succ == SI.getParent()->getNext())
1003 void CWriter::visitInvokeInst(InvokeInst &II) {
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);
1011 << " __llvm_jmpbuf_list = &Entry;\n"
1014 if (II.getType() != Type::VoidTy) outputLValue(&II);
1017 << " __llvm_jmpbuf_list = Entry.next;\n"
1019 printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1020 emittedInvoke = true;
1024 void 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.
1030 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"
1035 << " longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1036 emittedInvoke = true;
1039 static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1040 // If PHI nodes need copies, we need the copy code...
1041 if (isa<PHINode>(To->front()) ||
1042 From->getNext() != To) // Not directly successor, need goto
1045 // Otherwise we don't need the code.
1049 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1051 for (BasicBlock::iterator I = Succ->begin();
1052 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1053 // now we have to do the printing
1054 Out << std::string(Indent, ' ');
1055 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1056 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1057 Out << "; /* for PHI node */\n";
1060 if (CurBB->getNext() != Succ || isa<InvokeInst>(CurBB->getTerminator())) {
1061 Out << std::string(Indent, ' ') << " goto ";
1067 // Branch instruction printing - Avoid printing out a branch to a basic block
1068 // that immediately succeeds the current one.
1070 void CWriter::visitBranchInst(BranchInst &I) {
1071 if (I.isConditional()) {
1072 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1074 writeOperand(I.getCondition());
1077 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1079 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1080 Out << " } else {\n";
1081 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1084 // First goto not necessary, assume second one is...
1086 writeOperand(I.getCondition());
1089 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1094 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1099 // 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
1102 void CWriter::visitPHINode(PHINode &I) {
1104 Out << "__PHI_TEMPORARY";
1108 void CWriter::visitBinaryOperator(Instruction &I) {
1109 // binary instructions, shift instructions, setCond instructions.
1110 assert(!isa<PointerType>(I.getType()));
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)
1115 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1116 || (I.getType() == Type::FloatTy)) {
1119 printType(Out, I.getType(), "", false, false);
1123 writeOperand(I.getOperand(0));
1125 switch (I.getOpcode()) {
1126 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;
1142 default: std::cerr << "Invalid operator type!" << I; abort();
1145 writeOperand(I.getOperand(1));
1152 void CWriter::visitCastInst(CastInst &I) {
1153 if (I.getType() == Type::BoolTy) {
1155 writeOperand(I.getOperand(0));
1160 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1162 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
1168 writeOperand(I.getOperand(0));
1171 void CWriter::visitCallInst(CallInst &I) {
1172 // Handle intrinsic function calls first...
1173 if (Function *F = I.getCalledFunction())
1174 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1176 default: assert(0 && "Unknown LLVM intrinsic!");
1177 case LLVMIntrinsic::va_start:
1178 Out << "va_start(*(va_list*)";
1179 writeOperand(I.getOperand(1));
1181 // Output the last argument to the enclosing function...
1182 writeOperand(&I.getParent()->getParent()->aback());
1185 case LLVMIntrinsic::va_end:
1186 Out << "va_end(*(va_list*)";
1187 writeOperand(I.getOperand(1));
1190 case LLVMIntrinsic::va_copy:
1191 Out << "va_copy(*(va_list*)";
1192 writeOperand(I.getOperand(1));
1193 Out << ", (va_list)";
1194 writeOperand(I.getOperand(2));
1198 case LLVMIntrinsic::setjmp:
1199 case LLVMIntrinsic::sigsetjmp:
1200 // This intrinsic should never exist in the program, but until we get
1201 // setjmp/longjmp transformations going on, we should codegen it to
1202 // something reasonable. This will allow code that never calls longjmp
1206 case LLVMIntrinsic::longjmp:
1207 case LLVMIntrinsic::siglongjmp:
1208 // Longjmp is not implemented, and never will be. It would cause an
1217 void CWriter::visitCallSite(CallSite CS) {
1218 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1219 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1220 const Type *RetTy = FTy->getReturnType();
1222 writeOperand(CS.getCalledValue());
1225 if (CS.arg_begin() != CS.arg_end()) {
1226 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1229 for (++AI; AI != AE; ++AI) {
1237 void CWriter::visitMallocInst(MallocInst &I) {
1239 printType(Out, I.getType());
1240 Out << ")malloc(sizeof(";
1241 printType(Out, I.getType()->getElementType());
1244 if (I.isArrayAllocation()) {
1246 writeOperand(I.getOperand(0));
1251 void CWriter::visitAllocaInst(AllocaInst &I) {
1253 printType(Out, I.getType());
1254 Out << ") alloca(sizeof(";
1255 printType(Out, I.getType()->getElementType());
1257 if (I.isArrayAllocation()) {
1259 writeOperand(I.getOperand(0));
1264 void CWriter::visitFreeInst(FreeInst &I) {
1265 Out << "free((char*)";
1266 writeOperand(I.getOperand(0));
1270 void 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...
1279 } else if (isDirectAlloca(Ptr)) {
1280 HasImplicitAddress = true;
1284 if (!HasImplicitAddress)
1285 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1287 writeOperandInternal(Ptr);
1291 const Constant *CI = dyn_cast<Constant>(I);
1292 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1295 writeOperandInternal(Ptr);
1297 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1299 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1302 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1303 "Can only have implicit address with direct accessing");
1305 if (HasImplicitAddress) {
1307 } else if (CI && CI->isNullValue() && I+1 != E) {
1308 // Print out the -> operator if possible...
1309 if ((*(I+1))->getType() == Type::UByteTy) {
1310 Out << (HasImplicitAddress ? "." : "->");
1311 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1317 if ((*I)->getType() == Type::LongTy) {
1322 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1326 void CWriter::visitLoadInst(LoadInst &I) {
1328 writeOperand(I.getOperand(0));
1331 void CWriter::visitStoreInst(StoreInst &I) {
1333 writeOperand(I.getPointerOperand());
1335 writeOperand(I.getOperand(0));
1338 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1340 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1343 void CWriter::visitVarArgInst(VarArgInst &I) {
1344 Out << "va_arg((va_list)*";
1345 writeOperand(I.getOperand(0));
1347 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1352 //===----------------------------------------------------------------------===//
1353 // External Interface declaration
1354 //===----------------------------------------------------------------------===//
1356 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }