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.hasOneUse() ||
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 else if (I->hasWeakLinkage())
688 Out << " __attribute__((weak))";
689 if (!I->getInitializer()->isNullValue()) {
691 writeOperand(I->getInitializer());
697 // Output all floating point constants that cannot be printed accurately...
698 printFloatingPointConstants(*M);
700 // Output all of the functions...
701 emittedInvoke = false;
703 Out << "\n\n/* Function Bodies */\n";
704 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
708 // If the program included an invoke instruction, we need to output the
709 // support code for it here!
711 Out << "\n/* More support for the invoke instruction */\n"
712 << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
713 << "__attribute__((common)) = 0;\n";
716 // Done with global FP constants
717 FPConstantMap.clear();
720 /// Output all floating point constants that cannot be printed accurately...
721 void CWriter::printFloatingPointConstants(Module &M) {
724 unsigned long long U;
732 // Scan the module for floating point constants. If any FP constant is used
733 // in the function, we want to redirect it here so that we do not depend on
734 // the precision of the printed form, unless the printed form preserves
737 unsigned FPCounter = 0;
738 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
739 for (constant_iterator I = constant_begin(F), E = constant_end(F);
741 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
742 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
743 !FPConstantMap.count(FPC)) {
744 double Val = FPC->getValue();
746 FPConstantMap[FPC] = FPCounter; // Number the FP constants
748 if (FPC->getType() == Type::DoubleTy) {
750 Out << "const ConstantDoubleTy FPConstant" << FPCounter++
751 << " = 0x" << std::hex << DBLUnion.U << std::dec
752 << "ULL; /* " << Val << " */\n";
753 } else if (FPC->getType() == Type::FloatTy) {
755 Out << "const ConstantFloatTy FPConstant" << FPCounter++
756 << " = 0x" << std::hex << FLTUnion.U << std::dec
757 << "U; /* " << Val << " */\n";
759 assert(0 && "Unknown float type!");
766 /// printSymbolTable - Run through symbol table looking for type names. If a
767 /// type name is found, emit it's declaration...
769 void CWriter::printSymbolTable(const SymbolTable &ST) {
770 // If there are no type names, exit early.
771 if (ST.find(Type::TypeTy) == ST.end())
774 // We are only interested in the type plane of the symbol table...
775 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
776 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
778 // Print out forward declarations for structure types before anything else!
779 Out << "/* Structure forward decls */\n";
780 for (; I != End; ++I)
781 if (const Type *STy = dyn_cast<StructType>(I->second)) {
782 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
783 Out << Name << ";\n";
784 TypeNames.insert(std::make_pair(STy, Name));
789 // Now we can print out typedefs...
790 Out << "/* Typedefs */\n";
791 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
792 const Type *Ty = cast<Type>(I->second);
793 std::string Name = "l_" + Mangler::makeNameProper(I->first);
795 printType(Out, Ty, Name);
801 // Keep track of which structures have been printed so far...
802 std::set<const StructType *> StructPrinted;
804 // Loop over all structures then push them into the stack so they are
805 // printed in the correct order.
807 Out << "/* Structure contents */\n";
808 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
809 if (const StructType *STy = dyn_cast<StructType>(I->second))
810 printContainedStructs(STy, StructPrinted);
813 // Push the struct onto the stack and recursively push all structs
814 // this one depends on.
815 void CWriter::printContainedStructs(const Type *Ty,
816 std::set<const StructType*> &StructPrinted){
817 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
818 //Check to see if we have already printed this struct
819 if (StructPrinted.count(STy) == 0) {
820 // Print all contained types first...
821 for (StructType::ElementTypes::const_iterator
822 I = STy->getElementTypes().begin(),
823 E = STy->getElementTypes().end(); I != E; ++I) {
824 const Type *Ty1 = I->get();
825 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
826 printContainedStructs(*I, StructPrinted);
829 //Print structure type out..
830 StructPrinted.insert(STy);
831 std::string Name = TypeNames[STy];
832 printType(Out, STy, Name, true);
836 // If it is an array, check contained types and continue
837 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
838 const Type *Ty1 = ATy->getElementType();
839 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
840 printContainedStructs(Ty1, StructPrinted);
845 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
846 // If the program provides its own malloc prototype we don't need
847 // to include the general one.
848 if (Mang->getValueName(F) == "malloc")
851 if (F->hasInternalLinkage()) Out << "static ";
852 if (F->hasLinkOnceLinkage()) Out << "inline ";
854 // Loop over the arguments, printing them...
855 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
857 std::stringstream FunctionInnards;
859 // Print out the name...
860 FunctionInnards << Mang->getValueName(F) << "(";
862 if (!F->isExternal()) {
865 if (F->abegin()->hasName() || !Prototype)
866 ArgName = Mang->getValueName(F->abegin());
867 printType(FunctionInnards, F->afront().getType(), ArgName);
868 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
870 FunctionInnards << ", ";
871 if (I->hasName() || !Prototype)
872 ArgName = Mang->getValueName(I);
875 printType(FunctionInnards, I->getType(), ArgName);
879 // Loop over the arguments, printing them...
880 for (FunctionType::ParamTypes::const_iterator I =
881 FT->getParamTypes().begin(),
882 E = FT->getParamTypes().end(); I != E; ++I) {
883 if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
884 printType(FunctionInnards, *I);
888 // Finish printing arguments... if this is a vararg function, print the ...,
889 // unless there are no known types, in which case, we just emit ().
891 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
892 if (FT->getParamTypes().size()) FunctionInnards << ", ";
893 FunctionInnards << "..."; // Output varargs portion of signature!
895 FunctionInnards << ")";
896 // Print out the return type and the entire signature for that matter
897 printType(Out, F->getReturnType(), FunctionInnards.str());
899 if (F->hasWeakLinkage()) Out << " __attribute((weak))";
902 void CWriter::printFunction(Function *F) {
903 if (F->isExternal()) return;
905 printFunctionSignature(F, false);
908 // print local variable information for the function
909 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
910 if (const AllocaInst *AI = isDirectAlloca(*I)) {
912 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
913 Out << "; /* Address exposed local */\n";
914 } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
916 printType(Out, (*I)->getType(), Mang->getValueName(*I));
919 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
921 printType(Out, (*I)->getType(),
922 Mang->getValueName(*I)+"__PHI_TEMPORARY");
929 // print the basic blocks
930 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
931 BasicBlock *Prev = BB->getPrev();
933 // Don't print the label for the basic block if there are no uses, or if the
934 // only terminator use is the predecessor basic block's terminator. We have
935 // to scan the use list because PHI nodes use basic blocks too but do not
936 // require a label to be generated.
938 bool NeedsLabel = false;
939 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
941 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
942 if (TI != Prev->getTerminator() ||
943 isa<SwitchInst>(Prev->getTerminator()) ||
944 isa<InvokeInst>(Prev->getTerminator())) {
949 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
951 // Output all of the instructions in the basic block...
952 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
953 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
954 if (II->getType() != Type::VoidTy)
963 // Don't emit prefix or suffix for the terminator...
964 visit(*BB->getTerminator());
970 // Specific Instruction type classes... note that all of the casts are
971 // necessary because we use the instruction classes as opaque types...
973 void CWriter::visitReturnInst(ReturnInst &I) {
974 // Don't output a void return if this is the last basic block in the function
975 if (I.getNumOperands() == 0 &&
976 &*--I.getParent()->getParent()->end() == I.getParent() &&
977 !I.getParent()->size() == 1) {
982 if (I.getNumOperands()) {
984 writeOperand(I.getOperand(0));
989 void CWriter::visitSwitchInst(SwitchInst &SI) {
991 writeOperand(SI.getOperand(0));
992 Out << ") {\n default:\n";
993 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
995 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
997 writeOperand(SI.getOperand(i));
999 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1000 printBranchToBlock(SI.getParent(), Succ, 2);
1001 if (Succ == SI.getParent()->getNext())
1007 void CWriter::visitInvokeInst(InvokeInst &II) {
1009 << " struct __llvm_jmpbuf_list_t Entry;\n"
1010 << " Entry.next = __llvm_jmpbuf_list;\n"
1011 << " if (setjmp(Entry.buf)) {\n"
1012 << " __llvm_jmpbuf_list = Entry.next;\n";
1013 printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
1015 << " __llvm_jmpbuf_list = &Entry;\n"
1018 if (II.getType() != Type::VoidTy) outputLValue(&II);
1021 << " __llvm_jmpbuf_list = Entry.next;\n"
1023 printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
1024 emittedInvoke = true;
1028 void CWriter::visitUnwindInst(UnwindInst &I) {
1029 // The unwind instructions causes a control flow transfer out of the current
1030 // function, unwinding the stack until a caller who used the invoke
1031 // instruction is found. In this context, we code generated the invoke
1032 // instruction to add an entry to the top of the jmpbuf_list. Thus, here we
1033 // just have to longjmp to the specified handler.
1034 Out << " if (__llvm_jmpbuf_list == 0) { /* unwind */\n"
1035 << " extern write();\n"
1036 << " ((void (*)(int, void*, unsigned))write)(2,\n"
1037 << " \"throw found with no handler!\\n\", 31); abort();\n"
1039 << " longjmp(__llvm_jmpbuf_list->buf, 1);\n";
1040 emittedInvoke = true;
1043 static bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1044 // If PHI nodes need copies, we need the copy code...
1045 if (isa<PHINode>(To->front()) ||
1046 From->getNext() != To) // Not directly successor, need goto
1049 // Otherwise we don't need the code.
1053 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1055 for (BasicBlock::iterator I = Succ->begin();
1056 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1057 // now we have to do the printing
1058 Out << std::string(Indent, ' ');
1059 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1060 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1061 Out << "; /* for PHI node */\n";
1064 if (CurBB->getNext() != Succ ||
1065 isa<InvokeInst>(CurBB->getTerminator()) ||
1066 isa<SwitchInst>(CurBB->getTerminator())) {
1067 Out << std::string(Indent, ' ') << " goto ";
1073 // Branch instruction printing - Avoid printing out a branch to a basic block
1074 // that immediately succeeds the current one.
1076 void CWriter::visitBranchInst(BranchInst &I) {
1077 if (I.isConditional()) {
1078 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1080 writeOperand(I.getCondition());
1083 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1085 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1086 Out << " } else {\n";
1087 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1090 // First goto not necessary, assume second one is...
1092 writeOperand(I.getCondition());
1095 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1100 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1105 // PHI nodes get copied into temporary values at the end of predecessor basic
1106 // blocks. We now need to copy these temporary values into the REAL value for
1108 void CWriter::visitPHINode(PHINode &I) {
1110 Out << "__PHI_TEMPORARY";
1114 void CWriter::visitBinaryOperator(Instruction &I) {
1115 // binary instructions, shift instructions, setCond instructions.
1116 assert(!isa<PointerType>(I.getType()));
1118 // We must cast the results of binary operations which might be promoted.
1119 bool needsCast = false;
1120 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1121 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1122 || (I.getType() == Type::FloatTy)) {
1125 printType(Out, I.getType(), "", false, false);
1129 writeOperand(I.getOperand(0));
1131 switch (I.getOpcode()) {
1132 case Instruction::Add: Out << " + "; break;
1133 case Instruction::Sub: Out << " - "; break;
1134 case Instruction::Mul: Out << "*"; break;
1135 case Instruction::Div: Out << "/"; break;
1136 case Instruction::Rem: Out << "%"; break;
1137 case Instruction::And: Out << " & "; break;
1138 case Instruction::Or: Out << " | "; break;
1139 case Instruction::Xor: Out << " ^ "; break;
1140 case Instruction::SetEQ: Out << " == "; break;
1141 case Instruction::SetNE: Out << " != "; break;
1142 case Instruction::SetLE: Out << " <= "; break;
1143 case Instruction::SetGE: Out << " >= "; break;
1144 case Instruction::SetLT: Out << " < "; break;
1145 case Instruction::SetGT: Out << " > "; break;
1146 case Instruction::Shl : Out << " << "; break;
1147 case Instruction::Shr : Out << " >> "; break;
1148 default: std::cerr << "Invalid operator type!" << I; abort();
1151 writeOperand(I.getOperand(1));
1158 void CWriter::visitCastInst(CastInst &I) {
1159 if (I.getType() == Type::BoolTy) {
1161 writeOperand(I.getOperand(0));
1166 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1168 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1169 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1170 // Avoid "cast to pointer from integer of different size" warnings
1174 writeOperand(I.getOperand(0));
1177 void CWriter::visitCallInst(CallInst &I) {
1178 // Handle intrinsic function calls first...
1179 if (Function *F = I.getCalledFunction())
1180 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1182 default: assert(0 && "Unknown LLVM intrinsic!");
1183 case LLVMIntrinsic::va_start:
1184 Out << "va_start(*(va_list*)";
1185 writeOperand(I.getOperand(1));
1187 // Output the last argument to the enclosing function...
1188 writeOperand(&I.getParent()->getParent()->aback());
1191 case LLVMIntrinsic::va_end:
1192 Out << "va_end(*(va_list*)";
1193 writeOperand(I.getOperand(1));
1196 case LLVMIntrinsic::va_copy:
1197 Out << "va_copy(*(va_list*)";
1198 writeOperand(I.getOperand(1));
1199 Out << ", (va_list)";
1200 writeOperand(I.getOperand(2));
1204 case LLVMIntrinsic::setjmp:
1205 case LLVMIntrinsic::sigsetjmp:
1206 // This intrinsic should never exist in the program, but until we get
1207 // setjmp/longjmp transformations going on, we should codegen it to
1208 // something reasonable. This will allow code that never calls longjmp
1212 case LLVMIntrinsic::longjmp:
1213 case LLVMIntrinsic::siglongjmp:
1214 // Longjmp is not implemented, and never will be. It would cause an
1223 void CWriter::visitCallSite(CallSite CS) {
1224 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1225 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1226 const Type *RetTy = FTy->getReturnType();
1228 writeOperand(CS.getCalledValue());
1231 if (CS.arg_begin() != CS.arg_end()) {
1232 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1235 for (++AI; AI != AE; ++AI) {
1243 void CWriter::visitMallocInst(MallocInst &I) {
1245 printType(Out, I.getType());
1246 Out << ")malloc(sizeof(";
1247 printType(Out, I.getType()->getElementType());
1250 if (I.isArrayAllocation()) {
1252 writeOperand(I.getOperand(0));
1257 void CWriter::visitAllocaInst(AllocaInst &I) {
1259 printType(Out, I.getType());
1260 Out << ") alloca(sizeof(";
1261 printType(Out, I.getType()->getElementType());
1263 if (I.isArrayAllocation()) {
1265 writeOperand(I.getOperand(0));
1270 void CWriter::visitFreeInst(FreeInst &I) {
1271 Out << "free((char*)";
1272 writeOperand(I.getOperand(0));
1276 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1277 User::op_iterator E) {
1278 bool HasImplicitAddress = false;
1279 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1280 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1281 HasImplicitAddress = true;
1282 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1283 HasImplicitAddress = true;
1284 Ptr = CPR->getValue(); // Get to the global...
1285 } else if (isDirectAlloca(Ptr)) {
1286 HasImplicitAddress = true;
1290 if (!HasImplicitAddress)
1291 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1293 writeOperandInternal(Ptr);
1297 const Constant *CI = dyn_cast<Constant>(I);
1298 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1301 writeOperandInternal(Ptr);
1303 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1305 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1308 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1309 "Can only have implicit address with direct accessing");
1311 if (HasImplicitAddress) {
1313 } else if (CI && CI->isNullValue() && I+1 != E) {
1314 // Print out the -> operator if possible...
1315 if ((*(I+1))->getType() == Type::UByteTy) {
1316 Out << (HasImplicitAddress ? "." : "->");
1317 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1323 if ((*I)->getType() == Type::LongTy) {
1328 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1332 void CWriter::visitLoadInst(LoadInst &I) {
1334 writeOperand(I.getOperand(0));
1337 void CWriter::visitStoreInst(StoreInst &I) {
1339 writeOperand(I.getPointerOperand());
1341 writeOperand(I.getOperand(0));
1344 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1346 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1349 void CWriter::visitVarArgInst(VarArgInst &I) {
1350 Out << "va_arg((va_list)*";
1351 writeOperand(I.getOperand(0));
1353 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1358 //===----------------------------------------------------------------------===//
1359 // External Interface declaration
1360 //===----------------------------------------------------------------------===//
1362 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }