1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library converts LLVM code to C code, compilable by GCC and other C
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Assembly/CWriter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/SymbolTable.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Analysis/FindUsedTypes.h"
24 #include "llvm/Analysis/ConstantsScanner.h"
25 #include "llvm/Support/CallSite.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "llvm/Support/Mangler.h"
29 #include "Support/StringExtras.h"
35 class CWriter : public Pass, public InstVisitor<CWriter> {
38 const Module *TheModule;
41 std::map<const Type *, std::string> TypeNames;
42 std::set<const Value*> MangledGlobals;
43 bool needsMalloc, emittedInvoke;
45 std::map<const ConstantFP *, unsigned> FPConstantMap;
47 CWriter(std::ostream &o) : Out(o) {}
49 void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<FindUsedTypes>();
54 virtual bool run(Module &M) {
57 FUT = &getAnalysis<FindUsedTypes>();
59 // Ensure that all structure types have names...
60 bool Changed = nameAllUsedStructureTypes(M);
61 Mang = new Mangler(M);
69 MangledGlobals.clear();
73 std::ostream &printType(std::ostream &Out, const Type *Ty,
74 const std::string &VariableName = "",
75 bool IgnoreName = false);
77 void writeOperand(Value *Operand);
78 void writeOperandInternal(Value *Operand);
81 bool nameAllUsedStructureTypes(Module &M);
82 void printModule(Module *M);
83 void printFloatingPointConstants(Module &M);
84 void printSymbolTable(const SymbolTable &ST);
85 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
86 void printFunctionSignature(const Function *F, bool Prototype);
88 void printFunction(Function *);
90 void printConstant(Constant *CPV);
91 void printConstantArray(ConstantArray *CPA);
93 // isInlinableInst - Attempt to inline instructions into their uses to build
94 // trees as much as possible. To do this, we have to consistently decide
95 // what is acceptable to inline, so that variable declarations don't get
96 // printed and an extra copy of the expr is not emitted.
98 static bool isInlinableInst(const Instruction &I) {
99 // Must be an expression, must be used exactly once. If it is dead, we
100 // emit it inline where it would go.
101 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
102 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
103 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
104 // Don't inline a load across a store or other bad things!
107 // Only inline instruction it it's use is in the same BB as the inst.
108 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
111 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
112 // variables which are accessed with the & operator. This causes GCC to
113 // generate significantly better code than to emit alloca calls directly.
115 static const AllocaInst *isDirectAlloca(const Value *V) {
116 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
117 if (!AI) return false;
118 if (AI->isArrayAllocation())
119 return 0; // FIXME: we can also inline fixed size array allocas!
120 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
125 // Instruction visitation functions
126 friend class InstVisitor<CWriter>;
128 void visitReturnInst(ReturnInst &I);
129 void visitBranchInst(BranchInst &I);
130 void visitSwitchInst(SwitchInst &I);
131 void visitInvokeInst(InvokeInst &I);
132 void visitUnwindInst(UnwindInst &I);
134 void visitPHINode(PHINode &I);
135 void visitBinaryOperator(Instruction &I);
137 void visitCastInst (CastInst &I);
138 void visitCallInst (CallInst &I);
139 void visitCallSite (CallSite CS);
140 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
142 void visitMallocInst(MallocInst &I);
143 void visitAllocaInst(AllocaInst &I);
144 void visitFreeInst (FreeInst &I);
145 void visitLoadInst (LoadInst &I);
146 void visitStoreInst (StoreInst &I);
147 void visitGetElementPtrInst(GetElementPtrInst &I);
148 void visitVANextInst(VANextInst &I);
149 void visitVAArgInst (VAArgInst &I);
151 void visitInstruction(Instruction &I) {
152 std::cerr << "C Writer does not know about " << I;
156 void outputLValue(Instruction *I) {
157 Out << " " << Mang->getValueName(I) << " = ";
159 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
161 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
162 gep_type_iterator E);
165 // Pass the Type* and the variable name and this prints out the variable
168 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
169 const std::string &NameSoFar,
171 if (Ty->isPrimitiveType())
172 switch (Ty->getPrimitiveID()) {
173 case Type::VoidTyID: return Out << "void " << NameSoFar;
174 case Type::BoolTyID: return Out << "bool " << NameSoFar;
175 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
176 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
177 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
178 case Type::ShortTyID: return Out << "short " << NameSoFar;
179 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
180 case Type::IntTyID: return Out << "int " << NameSoFar;
181 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
182 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
183 case Type::FloatTyID: return Out << "float " << NameSoFar;
184 case Type::DoubleTyID: return Out << "double " << NameSoFar;
186 std::cerr << "Unknown primitive type: " << Ty << "\n";
190 // Check to see if the type is named.
191 if (!IgnoreName || isa<OpaqueType>(Ty)) {
192 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
193 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
196 switch (Ty->getPrimitiveID()) {
197 case Type::FunctionTyID: {
198 const FunctionType *MTy = cast<FunctionType>(Ty);
199 std::stringstream FunctionInnards;
200 FunctionInnards << " (" << NameSoFar << ") (";
201 for (FunctionType::param_iterator I = MTy->param_begin(),
202 E = MTy->param_end(); I != E; ++I) {
203 if (I != MTy->param_begin())
204 FunctionInnards << ", ";
205 printType(FunctionInnards, *I, "");
207 if (MTy->isVarArg()) {
208 if (MTy->getNumParams())
209 FunctionInnards << ", ...";
210 } else if (!MTy->getNumParams()) {
211 FunctionInnards << "void";
213 FunctionInnards << ")";
214 std::string tstr = FunctionInnards.str();
215 printType(Out, MTy->getReturnType(), tstr);
218 case Type::StructTyID: {
219 const StructType *STy = cast<StructType>(Ty);
220 Out << NameSoFar + " {\n";
222 for (StructType::element_iterator I = STy->element_begin(),
223 E = STy->element_end(); I != E; ++I) {
225 printType(Out, *I, "field" + utostr(Idx++));
231 case Type::PointerTyID: {
232 const PointerType *PTy = cast<PointerType>(Ty);
233 std::string ptrName = "*" + NameSoFar;
235 if (isa<ArrayType>(PTy->getElementType()))
236 ptrName = "(" + ptrName + ")";
238 return printType(Out, PTy->getElementType(), ptrName);
241 case Type::ArrayTyID: {
242 const ArrayType *ATy = cast<ArrayType>(Ty);
243 unsigned NumElements = ATy->getNumElements();
244 return printType(Out, ATy->getElementType(),
245 NameSoFar + "[" + utostr(NumElements) + "]");
248 case Type::OpaqueTyID: {
249 static int Count = 0;
250 std::string TyName = "struct opaque_" + itostr(Count++);
251 assert(TypeNames.find(Ty) == TypeNames.end());
252 TypeNames[Ty] = TyName;
253 return Out << TyName << " " << NameSoFar;
256 assert(0 && "Unhandled case in getTypeProps!");
263 void CWriter::printConstantArray(ConstantArray *CPA) {
265 // As a special case, print the array as a string if it is an array of
266 // ubytes or an array of sbytes with positive values.
268 const Type *ETy = CPA->getType()->getElementType();
269 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
271 // Make sure the last character is a null char, as automatically added by C
272 if (isString && (CPA->getNumOperands() == 0 ||
273 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
278 // Keep track of whether the last number was a hexadecimal escape
279 bool LastWasHex = false;
281 // Do not include the last character, which we know is null
282 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
283 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
285 // Print it out literally if it is a printable character. The only thing
286 // to be careful about is when the last letter output was a hex escape
287 // code, in which case we have to be careful not to print out hex digits
288 // explicitly (the C compiler thinks it is a continuation of the previous
289 // character, sheesh...)
291 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
293 if (C == '"' || C == '\\')
300 case '\n': Out << "\\n"; break;
301 case '\t': Out << "\\t"; break;
302 case '\r': Out << "\\r"; break;
303 case '\v': Out << "\\v"; break;
304 case '\a': Out << "\\a"; break;
305 case '\"': Out << "\\\""; break;
306 case '\'': Out << "\\\'"; break;
309 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
310 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
319 if (CPA->getNumOperands()) {
321 printConstant(cast<Constant>(CPA->getOperand(0)));
322 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
324 printConstant(cast<Constant>(CPA->getOperand(i)));
331 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
332 // textually as a double (rather than as a reference to a stack-allocated
333 // variable). We decide this by converting CFP to a string and back into a
334 // double, and then checking whether the conversion results in a bit-equal
335 // double to the original value of CFP. This depends on us and the target C
336 // compiler agreeing on the conversion process (which is pretty likely since we
337 // only deal in IEEE FP).
339 bool isFPCSafeToPrint(const ConstantFP *CFP) {
342 sprintf(Buffer, "%a", CFP->getValue());
344 if (!strncmp(Buffer, "0x", 2) ||
345 !strncmp(Buffer, "-0x", 3) ||
346 !strncmp(Buffer, "+0x", 3))
347 return atof(Buffer) == CFP->getValue();
350 std::string StrVal = ftostr(CFP->getValue());
352 while (StrVal[0] == ' ')
353 StrVal.erase(StrVal.begin());
355 // Check to make sure that the stringized number is not some string like "Inf"
356 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
357 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
358 ((StrVal[0] == '-' || StrVal[0] == '+') &&
359 (StrVal[1] >= '0' && StrVal[1] <= '9')))
360 // Reparse stringized version!
361 return atof(StrVal.c_str()) == CFP->getValue();
366 // printConstant - The LLVM Constant to C Constant converter.
367 void CWriter::printConstant(Constant *CPV) {
368 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
369 switch (CE->getOpcode()) {
370 case Instruction::Cast:
372 printType(Out, CPV->getType());
374 printConstant(CE->getOperand(0));
378 case Instruction::GetElementPtr:
380 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
384 case Instruction::Add:
385 case Instruction::Sub:
386 case Instruction::Mul:
387 case Instruction::Div:
388 case Instruction::Rem:
389 case Instruction::SetEQ:
390 case Instruction::SetNE:
391 case Instruction::SetLT:
392 case Instruction::SetLE:
393 case Instruction::SetGT:
394 case Instruction::SetGE:
395 case Instruction::Shl:
396 case Instruction::Shr:
398 printConstant(CE->getOperand(0));
399 switch (CE->getOpcode()) {
400 case Instruction::Add: Out << " + "; break;
401 case Instruction::Sub: Out << " - "; break;
402 case Instruction::Mul: Out << " * "; break;
403 case Instruction::Div: Out << " / "; break;
404 case Instruction::Rem: Out << " % "; break;
405 case Instruction::SetEQ: Out << " == "; break;
406 case Instruction::SetNE: Out << " != "; break;
407 case Instruction::SetLT: Out << " < "; break;
408 case Instruction::SetLE: Out << " <= "; break;
409 case Instruction::SetGT: Out << " > "; break;
410 case Instruction::SetGE: Out << " >= "; break;
411 case Instruction::Shl: Out << " << "; break;
412 case Instruction::Shr: Out << " >> "; break;
413 default: assert(0 && "Illegal opcode here!");
415 printConstant(CE->getOperand(1));
420 std::cerr << "CWriter Error: Unhandled constant expression: "
426 switch (CPV->getType()->getPrimitiveID()) {
428 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
429 case Type::SByteTyID:
430 case Type::ShortTyID:
431 Out << cast<ConstantSInt>(CPV)->getValue(); break;
433 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
434 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
436 Out << cast<ConstantSInt>(CPV)->getValue();
440 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
442 case Type::UByteTyID:
443 case Type::UShortTyID:
444 Out << cast<ConstantUInt>(CPV)->getValue(); break;
446 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
447 case Type::ULongTyID:
448 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
450 case Type::FloatTyID:
451 case Type::DoubleTyID: {
452 ConstantFP *FPC = cast<ConstantFP>(CPV);
453 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
454 if (I != FPConstantMap.end()) {
455 // Because of FP precision problems we must load from a stack allocated
456 // value that holds the value in hex.
457 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
458 << "*)&FPConstant" << I->second << ")";
461 // Print out the constant as a floating point number.
463 sprintf(Buffer, "%a", FPC->getValue());
464 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
466 Out << ftostr(FPC->getValue());
472 case Type::ArrayTyID:
473 printConstantArray(cast<ConstantArray>(CPV));
476 case Type::StructTyID: {
478 if (CPV->getNumOperands()) {
480 printConstant(cast<Constant>(CPV->getOperand(0)));
481 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
483 printConstant(cast<Constant>(CPV->getOperand(i)));
490 case Type::PointerTyID:
491 if (isa<ConstantPointerNull>(CPV)) {
493 printType(Out, CPV->getType());
494 Out << ")/*NULL*/0)";
496 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
497 writeOperand(CPR->getValue());
502 std::cerr << "Unknown constant type: " << CPV << "\n";
507 void CWriter::writeOperandInternal(Value *Operand) {
508 if (Instruction *I = dyn_cast<Instruction>(Operand))
509 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
510 // Should we inline this instruction to build a tree?
517 if (Constant *CPV = dyn_cast<Constant>(Operand)) {
520 Out << Mang->getValueName(Operand);
524 void CWriter::writeOperand(Value *Operand) {
525 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
526 Out << "(&"; // Global variables are references as their addresses by llvm
528 writeOperandInternal(Operand);
530 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
534 // nameAllUsedStructureTypes - If there are structure types in the module that
535 // are used but do not have names assigned to them in the symbol table yet then
536 // we assign them names now.
538 bool CWriter::nameAllUsedStructureTypes(Module &M) {
539 // Get a set of types that are used by the program...
540 std::set<const Type *> UT = FUT->getTypes();
542 // Loop over the module symbol table, removing types from UT that are already
545 SymbolTable &MST = M.getSymbolTable();
546 if (MST.find(Type::TypeTy) != MST.end())
547 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
548 E = MST.type_end(Type::TypeTy); I != E; ++I)
549 UT.erase(cast<Type>(I->second));
551 // UT now contains types that are not named. Loop over it, naming structure
554 bool Changed = false;
555 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
557 if (const StructType *ST = dyn_cast<StructType>(*I)) {
558 ((Value*)ST)->setName("unnamed", &MST);
564 // generateCompilerSpecificCode - This is where we add conditional compilation
565 // directives to cater to specific compilers as need be.
567 static void generateCompilerSpecificCode(std::ostream& Out) {
568 // Alloca is hard to get, and we don't want to include stdlib.h here...
569 Out << "/* get a declaration for alloca */\n"
571 << "extern void *__builtin_alloca(unsigned long);\n"
572 << "#define alloca(x) __builtin_alloca(x)\n"
574 << "#ifndef __FreeBSD__\n"
575 << "#include <alloca.h>\n"
579 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
580 // If we aren't being compiled with GCC, just drop these attributes.
581 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
582 << "#define __attribute__(X)\n"
586 // At some point, we should support "external weak" vs. "weak" linkages.
587 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
588 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
589 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
590 << "#elif defined(__GNUC__)\n"
591 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
593 << "#define __EXTERNAL_WEAK__\n"
597 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
598 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
599 << "#define __ATTRIBUTE_WEAK__\n"
600 << "#elif defined(__GNUC__)\n"
601 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
603 << "#define __ATTRIBUTE_WEAK__\n"
607 // generateProcessorSpecificCode - This is where we add conditional compilation
608 // directives to cater to specific processors as need be.
610 static void generateProcessorSpecificCode(std::ostream& Out) {
611 // According to ANSI C, longjmp'ing to a setjmp could invalidate any
612 // non-volatile variable in the scope of the setjmp. For now, we are not
613 // doing analysis to determine which variables need to be marked volatile, so
614 // we just mark them all.
616 // HOWEVER, many targets implement setjmp by saving and restoring the register
617 // file, so they DON'T need variables to be marked volatile, and this is a
618 // HUGE pessimization for them. For this reason, on known-good processors, we
619 // do not emit volatile qualifiers.
620 Out << "#if defined(__386__) || defined(__i386__) || \\\n"
621 << " defined(i386) || defined(WIN32)\n"
622 << "/* setjmp does not require variables to be marked volatile */"
623 << "#define VOLATILE_FOR_SETJMP\n"
625 << "#define VOLATILE_FOR_SETJMP volatile\n"
630 void CWriter::printModule(Module *M) {
631 // Calculate which global values have names that will collide when we throw
632 // away type information.
633 { // Scope to delete the FoundNames set when we are done with it...
634 std::set<std::string> FoundNames;
635 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
636 if (I->hasName()) // If the global has a name...
637 if (FoundNames.count(I->getName())) // And the name is already used
638 MangledGlobals.insert(I); // Mangle the name
640 FoundNames.insert(I->getName()); // Otherwise, keep track of name
642 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
643 if (I->hasName()) // If the global has a name...
644 if (FoundNames.count(I->getName())) // And the name is already used
645 MangledGlobals.insert(I); // Mangle the name
647 FoundNames.insert(I->getName()); // Otherwise, keep track of name
650 // get declaration for alloca
651 Out << "/* Provide Declarations */\n";
652 Out << "#include <stdarg.h>\n"; // Varargs support
653 Out << "#include <setjmp.h>\n"; // Unwind support
654 generateCompilerSpecificCode(Out);
655 generateProcessorSpecificCode(Out);
657 // Provide a definition for `bool' if not compiling with a C++ compiler.
659 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
661 << "\n\n/* Support for floating point constants */\n"
662 << "typedef unsigned long long ConstantDoubleTy;\n"
663 << "typedef unsigned int ConstantFloatTy;\n"
665 << "\n\n/* Support for the invoke instruction */\n"
666 << "extern struct __llvm_jmpbuf_list_t {\n"
667 << " jmp_buf buf; struct __llvm_jmpbuf_list_t *next;\n"
668 << "} *__llvm_jmpbuf_list;\n"
670 << "\n\n/* Global Declarations */\n";
672 // First output all the declarations for the program, because C requires
673 // Functions & globals to be declared before they are used.
676 // Loop over the symbol table, emitting all named constants...
677 printSymbolTable(M->getSymbolTable());
679 // Global variable declarations...
681 Out << "\n/* External Global Variable Declarations */\n";
682 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
683 if (I->hasExternalLinkage()) {
685 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
691 // Function declarations
693 Out << "\n/* Function Declarations */\n";
695 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
696 // If the function is external and the name collides don't print it.
697 // Sometimes the bytecode likes to have multiple "declarations" for
698 // external functions
699 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
700 !I->getIntrinsicID()) {
701 printFunctionSignature(I, true);
702 if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
708 // Print Malloc prototype if needed
710 Out << "\n/* Malloc to make sun happy */\n";
711 Out << "extern void * malloc();\n\n";
714 // Output the global variable declarations
716 Out << "\n\n/* Global Variable Declarations */\n";
717 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
718 if (!I->isExternal()) {
720 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
722 if (I->hasLinkOnceLinkage())
723 Out << " __attribute__((common))";
724 else if (I->hasWeakLinkage())
725 Out << " __ATTRIBUTE_WEAK__";
730 // Output the global variable definitions and contents...
732 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
733 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
734 if (!I->isExternal()) {
735 if (I->hasInternalLinkage())
737 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
738 if (I->hasLinkOnceLinkage())
739 Out << " __attribute__((common))";
740 else if (I->hasWeakLinkage())
741 Out << " __ATTRIBUTE_WEAK__";
743 // If the initializer is not null, emit the initializer. If it is null,
744 // we try to avoid emitting large amounts of zeros. The problem with
745 // this, however, occurs when the variable has weak linkage. In this
746 // case, the assembler will complain about the variable being both weak
747 // and common, so we disable this optimization.
748 if (!I->getInitializer()->isNullValue() ||
749 I->hasWeakLinkage()) {
751 writeOperand(I->getInitializer());
757 // Output all floating point constants that cannot be printed accurately...
758 printFloatingPointConstants(*M);
760 // Output all of the functions...
761 emittedInvoke = false;
763 Out << "\n\n/* Function Bodies */\n";
764 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
768 // If the program included an invoke instruction, we need to output the
769 // support code for it here!
771 Out << "\n/* More support for the invoke instruction */\n"
772 << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
773 << "__attribute__((common)) = 0;\n";
776 // Done with global FP constants
777 FPConstantMap.clear();
780 /// Output all floating point constants that cannot be printed accurately...
781 void CWriter::printFloatingPointConstants(Module &M) {
784 unsigned long long U;
792 // Scan the module for floating point constants. If any FP constant is used
793 // in the function, we want to redirect it here so that we do not depend on
794 // the precision of the printed form, unless the printed form preserves
797 unsigned FPCounter = 0;
798 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
799 for (constant_iterator I = constant_begin(F), E = constant_end(F);
801 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
802 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
803 !FPConstantMap.count(FPC)) {
804 double Val = FPC->getValue();
806 FPConstantMap[FPC] = FPCounter; // Number the FP constants
808 if (FPC->getType() == Type::DoubleTy) {
810 Out << "const ConstantDoubleTy FPConstant" << FPCounter++
811 << " = 0x" << std::hex << DBLUnion.U << std::dec
812 << "ULL; /* " << Val << " */\n";
813 } else if (FPC->getType() == Type::FloatTy) {
815 Out << "const ConstantFloatTy FPConstant" << FPCounter++
816 << " = 0x" << std::hex << FLTUnion.U << std::dec
817 << "U; /* " << Val << " */\n";
819 assert(0 && "Unknown float type!");
826 /// printSymbolTable - Run through symbol table looking for type names. If a
827 /// type name is found, emit it's declaration...
829 void CWriter::printSymbolTable(const SymbolTable &ST) {
830 // If there are no type names, exit early.
831 if (ST.find(Type::TypeTy) == ST.end())
834 // We are only interested in the type plane of the symbol table...
835 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
836 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
838 // Print out forward declarations for structure types before anything else!
839 Out << "/* Structure forward decls */\n";
840 for (; I != End; ++I)
841 if (const Type *STy = dyn_cast<StructType>(I->second))
842 // Only print out used types!
843 if (FUT->getTypes().count(STy)) {
844 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
845 Out << Name << ";\n";
846 TypeNames.insert(std::make_pair(STy, Name));
851 // Now we can print out typedefs...
852 Out << "/* Typedefs */\n";
853 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
854 // Only print out used types!
855 if (FUT->getTypes().count(cast<Type>(I->second))) {
856 const Type *Ty = cast<Type>(I->second);
857 std::string Name = "l_" + Mangler::makeNameProper(I->first);
859 printType(Out, Ty, Name);
865 // Keep track of which structures have been printed so far...
866 std::set<const StructType *> StructPrinted;
868 // Loop over all structures then push them into the stack so they are
869 // printed in the correct order.
871 Out << "/* Structure contents */\n";
872 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
873 if (const StructType *STy = dyn_cast<StructType>(I->second))
874 // Only print out used types!
875 if (FUT->getTypes().count(STy))
876 printContainedStructs(STy, StructPrinted);
879 // Push the struct onto the stack and recursively push all structs
880 // this one depends on.
881 void CWriter::printContainedStructs(const Type *Ty,
882 std::set<const StructType*> &StructPrinted){
883 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
884 //Check to see if we have already printed this struct
885 if (StructPrinted.count(STy) == 0) {
886 // Print all contained types first...
887 for (StructType::element_iterator I = STy->element_begin(),
888 E = STy->element_end(); I != E; ++I) {
889 const Type *Ty1 = I->get();
890 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
891 printContainedStructs(*I, StructPrinted);
894 //Print structure type out..
895 StructPrinted.insert(STy);
896 std::string Name = TypeNames[STy];
897 printType(Out, STy, Name, true);
901 // If it is an array, check contained types and continue
902 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
903 const Type *Ty1 = ATy->getElementType();
904 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
905 printContainedStructs(Ty1, StructPrinted);
910 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
911 // If the program provides its own malloc prototype we don't need
912 // to include the general one.
913 if (Mang->getValueName(F) == "malloc")
916 if (F->hasInternalLinkage()) Out << "static ";
917 if (F->hasLinkOnceLinkage()) Out << "inline ";
919 // Loop over the arguments, printing them...
920 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
922 std::stringstream FunctionInnards;
924 // Print out the name...
925 FunctionInnards << Mang->getValueName(F) << "(";
927 if (!F->isExternal()) {
930 if (F->abegin()->hasName() || !Prototype)
931 ArgName = Mang->getValueName(F->abegin());
932 printType(FunctionInnards, F->afront().getType(), ArgName);
933 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
935 FunctionInnards << ", ";
936 if (I->hasName() || !Prototype)
937 ArgName = Mang->getValueName(I);
940 printType(FunctionInnards, I->getType(), ArgName);
944 // Loop over the arguments, printing them...
945 for (FunctionType::param_iterator I = FT->param_begin(),
946 E = FT->param_end(); I != E; ++I) {
947 if (I != FT->param_begin()) FunctionInnards << ", ";
948 printType(FunctionInnards, *I);
952 // Finish printing arguments... if this is a vararg function, print the ...,
953 // unless there are no known types, in which case, we just emit ().
955 if (FT->isVarArg() && FT->getNumParams()) {
956 if (FT->getNumParams()) FunctionInnards << ", ";
957 FunctionInnards << "..."; // Output varargs portion of signature!
958 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
959 FunctionInnards << "void"; // ret() -> ret(void) in C.
961 FunctionInnards << ")";
962 // Print out the return type and the entire signature for that matter
963 printType(Out, F->getReturnType(), FunctionInnards.str());
966 void CWriter::printFunction(Function *F) {
967 if (F->isExternal()) return;
969 printFunctionSignature(F, false);
972 // Determine whether or not the function contains any invoke instructions.
973 bool HasInvoke = false;
974 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
975 if (isa<InvokeInst>(I->getTerminator())) {
980 // print local variable information for the function
981 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
982 if (const AllocaInst *AI = isDirectAlloca(*I)) {
984 if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
985 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
986 Out << "; /* Address exposed local */\n";
987 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
989 if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
990 printType(Out, (*I)->getType(), Mang->getValueName(*I));
993 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
995 if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
996 printType(Out, (*I)->getType(),
997 Mang->getValueName(*I)+"__PHI_TEMPORARY");
1004 // print the basic blocks
1005 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1006 BasicBlock *Prev = BB->getPrev();
1008 // Don't print the label for the basic block if there are no uses, or if the
1009 // only terminator use is the predecessor basic block's terminator. We have
1010 // to scan the use list because PHI nodes use basic blocks too but do not
1011 // require a label to be generated.
1013 bool NeedsLabel = false;
1014 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
1016 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
1017 if (TI != Prev->getTerminator() ||
1018 isa<SwitchInst>(Prev->getTerminator()) ||
1019 isa<InvokeInst>(Prev->getTerminator())) {
1024 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1026 // Output all of the instructions in the basic block...
1027 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
1028 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1029 if (II->getType() != Type::VoidTy)
1038 // Don't emit prefix or suffix for the terminator...
1039 visit(*BB->getTerminator());
1045 // Specific Instruction type classes... note that all of the casts are
1046 // necessary because we use the instruction classes as opaque types...
1048 void CWriter::visitReturnInst(ReturnInst &I) {
1049 // Don't output a void return if this is the last basic block in the function
1050 if (I.getNumOperands() == 0 &&
1051 &*--I.getParent()->getParent()->end() == I.getParent() &&
1052 !I.getParent()->size() == 1) {
1057 if (I.getNumOperands()) {
1059 writeOperand(I.getOperand(0));
1064 void CWriter::visitSwitchInst(SwitchInst &SI) {
1066 writeOperand(SI.getOperand(0));
1067 Out << ") {\n default:\n";
1068 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1070 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1072 writeOperand(SI.getOperand(i));
1074 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1075 printBranchToBlock(SI.getParent(), Succ, 2);
1076 if (Succ == SI.getParent()->getNext())
1082 void CWriter::visitInvokeInst(InvokeInst &II) {
1084 << " struct __llvm_jmpbuf_list_t Entry;\n"
1085 << " Entry.next = __llvm_jmpbuf_list;\n"
1086 << " if (setjmp(Entry.buf)) {\n"
1087 << " __llvm_jmpbuf_list = Entry.next;\n";
1088 printBranchToBlock(II.getParent(), II.getUnwindDest(), 4);
1090 << " __llvm_jmpbuf_list = &Entry;\n"
1093 if (II.getType() != Type::VoidTy) outputLValue(&II);
1096 << " __llvm_jmpbuf_list = Entry.next;\n"
1098 printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1099 emittedInvoke = true;
1103 void CWriter::visitUnwindInst(UnwindInst &I) {
1104 // The unwind instructions causes a control flow transfer out of the current
1105 // function, unwinding the stack until a caller who used the invoke
1106 // instruction is found. In this context, we code generated the invoke
1107 // instruction to add an entry to the top of the jmpbuf_list. Thus, here we
1108 // just have to longjmp to the specified handler.
1109 Out << " if (__llvm_jmpbuf_list == 0) { /* unwind */\n"
1111 << " extern signed long long write();\n"
1113 << " extern write();\n"
1115 << " ((void (*)(int, void*, unsigned))write)(2,\n"
1116 << " \"throw found with no handler!\\n\", 31); abort();\n"
1118 << " longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1119 emittedInvoke = true;
1122 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1123 // If PHI nodes need copies, we need the copy code...
1124 if (isa<PHINode>(To->front()) ||
1125 From->getNext() != To) // Not directly successor, need goto
1128 // Otherwise we don't need the code.
1132 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1134 for (BasicBlock::iterator I = Succ->begin();
1135 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1136 // now we have to do the printing
1137 Out << std::string(Indent, ' ');
1138 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1139 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1140 Out << "; /* for PHI node */\n";
1143 if (CurBB->getNext() != Succ ||
1144 isa<InvokeInst>(CurBB->getTerminator()) ||
1145 isa<SwitchInst>(CurBB->getTerminator())) {
1146 Out << std::string(Indent, ' ') << " goto ";
1152 // Branch instruction printing - Avoid printing out a branch to a basic block
1153 // that immediately succeeds the current one.
1155 void CWriter::visitBranchInst(BranchInst &I) {
1156 if (I.isConditional()) {
1157 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1159 writeOperand(I.getCondition());
1162 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1164 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1165 Out << " } else {\n";
1166 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1169 // First goto not necessary, assume second one is...
1171 writeOperand(I.getCondition());
1174 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1179 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1184 // PHI nodes get copied into temporary values at the end of predecessor basic
1185 // blocks. We now need to copy these temporary values into the REAL value for
1187 void CWriter::visitPHINode(PHINode &I) {
1189 Out << "__PHI_TEMPORARY";
1193 void CWriter::visitBinaryOperator(Instruction &I) {
1194 // binary instructions, shift instructions, setCond instructions.
1195 assert(!isa<PointerType>(I.getType()));
1197 // We must cast the results of binary operations which might be promoted.
1198 bool needsCast = false;
1199 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1200 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1201 || (I.getType() == Type::FloatTy)) {
1204 printType(Out, I.getType());
1208 writeOperand(I.getOperand(0));
1210 switch (I.getOpcode()) {
1211 case Instruction::Add: Out << " + "; break;
1212 case Instruction::Sub: Out << " - "; break;
1213 case Instruction::Mul: Out << "*"; break;
1214 case Instruction::Div: Out << "/"; break;
1215 case Instruction::Rem: Out << "%"; break;
1216 case Instruction::And: Out << " & "; break;
1217 case Instruction::Or: Out << " | "; break;
1218 case Instruction::Xor: Out << " ^ "; break;
1219 case Instruction::SetEQ: Out << " == "; break;
1220 case Instruction::SetNE: Out << " != "; break;
1221 case Instruction::SetLE: Out << " <= "; break;
1222 case Instruction::SetGE: Out << " >= "; break;
1223 case Instruction::SetLT: Out << " < "; break;
1224 case Instruction::SetGT: Out << " > "; break;
1225 case Instruction::Shl : Out << " << "; break;
1226 case Instruction::Shr : Out << " >> "; break;
1227 default: std::cerr << "Invalid operator type!" << I; abort();
1230 writeOperand(I.getOperand(1));
1237 void CWriter::visitCastInst(CastInst &I) {
1238 if (I.getType() == Type::BoolTy) {
1240 writeOperand(I.getOperand(0));
1245 printType(Out, I.getType());
1247 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1248 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1249 // Avoid "cast to pointer from integer of different size" warnings
1253 writeOperand(I.getOperand(0));
1256 void CWriter::visitCallInst(CallInst &I) {
1257 // Handle intrinsic function calls first...
1258 if (Function *F = I.getCalledFunction())
1259 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1261 default: assert(0 && "Unknown LLVM intrinsic!");
1262 case Intrinsic::va_start:
1265 Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1266 // Output the last argument to the enclosing function...
1267 if (I.getParent()->getParent()->aempty()) {
1268 std::cerr << "The C backend does not currently support zero "
1269 << "argument varargs functions, such as '"
1270 << I.getParent()->getParent()->getName() << "'!\n";
1273 writeOperand(&I.getParent()->getParent()->aback());
1276 case Intrinsic::va_end:
1277 Out << "va_end(*(va_list*)&";
1278 writeOperand(I.getOperand(1));
1281 case Intrinsic::va_copy:
1283 Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1284 Out << "*(va_list*)&";
1285 writeOperand(I.getOperand(1));
1288 case Intrinsic::setjmp:
1289 case Intrinsic::sigsetjmp:
1290 // This intrinsic should never exist in the program, but until we get
1291 // setjmp/longjmp transformations going on, we should codegen it to
1292 // something reasonable. This will allow code that never calls longjmp
1296 case Intrinsic::longjmp:
1297 case Intrinsic::siglongjmp:
1298 // Longjmp is not implemented, and never will be. It would cause an
1302 case Intrinsic::memcpy:
1304 writeOperand(I.getOperand(1));
1306 writeOperand(I.getOperand(2));
1308 writeOperand(I.getOperand(3));
1311 case Intrinsic::memmove:
1313 writeOperand(I.getOperand(1));
1315 writeOperand(I.getOperand(2));
1317 writeOperand(I.getOperand(3));
1325 void CWriter::visitCallSite(CallSite CS) {
1326 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1327 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1328 const Type *RetTy = FTy->getReturnType();
1330 writeOperand(CS.getCalledValue());
1333 if (CS.arg_begin() != CS.arg_end()) {
1334 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1337 for (++AI; AI != AE; ++AI) {
1345 void CWriter::visitMallocInst(MallocInst &I) {
1347 printType(Out, I.getType());
1348 Out << ")malloc(sizeof(";
1349 printType(Out, I.getType()->getElementType());
1352 if (I.isArrayAllocation()) {
1354 writeOperand(I.getOperand(0));
1359 void CWriter::visitAllocaInst(AllocaInst &I) {
1361 printType(Out, I.getType());
1362 Out << ") alloca(sizeof(";
1363 printType(Out, I.getType()->getElementType());
1365 if (I.isArrayAllocation()) {
1367 writeOperand(I.getOperand(0));
1372 void CWriter::visitFreeInst(FreeInst &I) {
1373 Out << "free((char*)";
1374 writeOperand(I.getOperand(0));
1378 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1379 gep_type_iterator E) {
1380 bool HasImplicitAddress = false;
1381 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1382 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1383 HasImplicitAddress = true;
1384 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1385 HasImplicitAddress = true;
1386 Ptr = CPR->getValue(); // Get to the global...
1387 } else if (isDirectAlloca(Ptr)) {
1388 HasImplicitAddress = true;
1392 if (!HasImplicitAddress)
1393 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1395 writeOperandInternal(Ptr);
1399 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1400 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1403 writeOperandInternal(Ptr);
1405 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1407 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1410 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1411 "Can only have implicit address with direct accessing");
1413 if (HasImplicitAddress) {
1415 } else if (CI && CI->isNullValue()) {
1416 gep_type_iterator TmpI = I; ++TmpI;
1418 // Print out the -> operator if possible...
1419 if (TmpI != E && isa<StructType>(*TmpI)) {
1420 Out << (HasImplicitAddress ? "." : "->");
1421 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1427 if (isa<StructType>(*I)) {
1428 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1431 writeOperand(I.getOperand());
1436 void CWriter::visitLoadInst(LoadInst &I) {
1438 writeOperand(I.getOperand(0));
1441 void CWriter::visitStoreInst(StoreInst &I) {
1443 writeOperand(I.getPointerOperand());
1445 writeOperand(I.getOperand(0));
1448 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1450 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1454 void CWriter::visitVANextInst(VANextInst &I) {
1455 Out << Mang->getValueName(I.getOperand(0));
1456 Out << "; va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1457 printType(Out, I.getArgType());
1461 void CWriter::visitVAArgInst(VAArgInst &I) {
1463 Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1464 writeOperand(I.getOperand(0));
1465 Out << ");\n " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1466 printType(Out, I.getType());
1467 Out << ");\n va_end(Tmp); }";
1472 //===----------------------------------------------------------------------===//
1473 // External Interface declaration
1474 //===----------------------------------------------------------------------===//
1476 Pass *llvm::createWriteToCPass(std::ostream &o) { return new CWriter(o); }