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 "CTargetMachine.h"
16 #include "llvm/Target/TargetMachineImpls.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicLowering.h"
26 #include "llvm/Analysis/ConstantsScanner.h"
27 #include "llvm/Analysis/FindUsedTypes.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/InstVisitor.h"
34 #include "llvm/Support/Mangler.h"
35 #include "Support/StringExtras.h"
36 #include "Config/config.h"
42 /// NameAllUsedStructs - This pass inserts names for any unnamed structure
43 /// types that are used by the program.
45 class CBackendNameAllUsedStructs : public Pass {
46 void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequired<FindUsedTypes>();
50 virtual const char *getPassName() const {
51 return "C backend type canonicalizer";
54 virtual bool run(Module &M);
57 /// CWriter - This class is the main chunk of code that converts an LLVM
58 /// module to a C translation unit.
59 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
61 IntrinsicLowering &IL;
64 const Module *TheModule;
65 std::map<const Type *, std::string> TypeNames;
67 std::map<const ConstantFP *, unsigned> FPConstantMap;
69 CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
71 virtual const char *getPassName() const { return "C backend"; }
73 void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<LoopInfo>();
78 virtual bool doInitialization(Module &M);
80 bool runOnFunction(Function &F) {
81 LI = &getAnalysis<LoopInfo>();
83 // Output all floating point constants that cannot be printed accurately.
84 printFloatingPointConstants(F);
88 FPConstantMap.clear();
92 virtual bool doFinalization(Module &M) {
99 std::ostream &printType(std::ostream &Out, const Type *Ty,
100 const std::string &VariableName = "",
101 bool IgnoreName = false);
103 void writeOperand(Value *Operand);
104 void writeOperandInternal(Value *Operand);
107 void lowerIntrinsics(Function &F);
109 bool nameAllUsedStructureTypes(Module &M);
110 void printModule(Module *M);
111 void printModuleTypes(const SymbolTable &ST);
112 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
113 void printFloatingPointConstants(Function &F);
114 void printFunctionSignature(const Function *F, bool Prototype);
116 void printFunction(Function &);
117 void printBasicBlock(BasicBlock *BB);
118 void printLoop(Loop *L);
120 void printConstant(Constant *CPV);
121 void printConstantArray(ConstantArray *CPA);
123 // isInlinableInst - Attempt to inline instructions into their uses to build
124 // trees as much as possible. To do this, we have to consistently decide
125 // what is acceptable to inline, so that variable declarations don't get
126 // printed and an extra copy of the expr is not emitted.
128 static bool isInlinableInst(const Instruction &I) {
129 // Always inline setcc instructions, even if they are shared by multiple
130 // expressions. GCC generates horrible code if we don't.
131 if (isa<SetCondInst>(I)) return true;
133 // Must be an expression, must be used exactly once. If it is dead, we
134 // emit it inline where it would go.
135 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
136 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
137 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
138 // Don't inline a load across a store or other bad things!
141 // Only inline instruction it it's use is in the same BB as the inst.
142 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
145 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
146 // variables which are accessed with the & operator. This causes GCC to
147 // generate significantly better code than to emit alloca calls directly.
149 static const AllocaInst *isDirectAlloca(const Value *V) {
150 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
151 if (!AI) return false;
152 if (AI->isArrayAllocation())
153 return 0; // FIXME: we can also inline fixed size array allocas!
154 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
159 // Instruction visitation functions
160 friend class InstVisitor<CWriter>;
162 void visitReturnInst(ReturnInst &I);
163 void visitBranchInst(BranchInst &I);
164 void visitSwitchInst(SwitchInst &I);
165 void visitInvokeInst(InvokeInst &I) {
166 assert(0 && "Lowerinvoke pass didn't work!");
169 void visitUnwindInst(UnwindInst &I) {
170 assert(0 && "Lowerinvoke pass didn't work!");
173 void visitPHINode(PHINode &I);
174 void visitBinaryOperator(Instruction &I);
176 void visitCastInst (CastInst &I);
177 void visitSelectInst(SelectInst &I);
178 void visitCallInst (CallInst &I);
179 void visitCallSite (CallSite CS);
180 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
182 void visitMallocInst(MallocInst &I);
183 void visitAllocaInst(AllocaInst &I);
184 void visitFreeInst (FreeInst &I);
185 void visitLoadInst (LoadInst &I);
186 void visitStoreInst (StoreInst &I);
187 void visitGetElementPtrInst(GetElementPtrInst &I);
188 void visitVANextInst(VANextInst &I);
189 void visitVAArgInst (VAArgInst &I);
191 void visitInstruction(Instruction &I) {
192 std::cerr << "C Writer does not know about " << I;
196 void outputLValue(Instruction *I) {
197 Out << " " << Mang->getValueName(I) << " = ";
200 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
201 void printPHICopiesForSuccessors(BasicBlock *CurBlock,
203 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
205 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
206 gep_type_iterator E);
210 /// This method inserts names for any unnamed structure types that are used by
211 /// the program, and removes names from structure types that are not used by the
214 bool CBackendNameAllUsedStructs::run(Module &M) {
215 // Get a set of types that are used by the program...
216 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
218 // Loop over the module symbol table, removing types from UT that are
219 // already named, and removing names for structure types that are not used.
221 SymbolTable &MST = M.getSymbolTable();
222 if (MST.find(Type::TypeTy) != MST.end())
223 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
224 E = MST.type_end(Type::TypeTy); I != E; ) {
225 SymbolTable::type_iterator It = I++;
226 if (StructType *STy = dyn_cast<StructType>(It->second)) {
227 // If this is not used, remove it from the symbol table.
228 std::set<const Type *>::iterator UTI = UT.find(STy);
230 MST.remove(It->first, It->second);
236 // UT now contains types that are not named. Loop over it, naming
239 bool Changed = false;
240 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
242 if (const StructType *ST = dyn_cast<StructType>(*I)) {
243 ((Value*)ST)->setName("unnamed", &MST);
250 // Pass the Type* and the variable name and this prints out the variable
253 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
254 const std::string &NameSoFar,
256 if (Ty->isPrimitiveType())
257 switch (Ty->getPrimitiveID()) {
258 case Type::VoidTyID: return Out << "void " << NameSoFar;
259 case Type::BoolTyID: return Out << "bool " << NameSoFar;
260 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
261 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
262 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
263 case Type::ShortTyID: return Out << "short " << NameSoFar;
264 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
265 case Type::IntTyID: return Out << "int " << NameSoFar;
266 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
267 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
268 case Type::FloatTyID: return Out << "float " << NameSoFar;
269 case Type::DoubleTyID: return Out << "double " << NameSoFar;
271 std::cerr << "Unknown primitive type: " << Ty << "\n";
275 // Check to see if the type is named.
276 if (!IgnoreName || isa<OpaqueType>(Ty)) {
277 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
278 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
281 switch (Ty->getPrimitiveID()) {
282 case Type::FunctionTyID: {
283 const FunctionType *MTy = cast<FunctionType>(Ty);
284 std::stringstream FunctionInnards;
285 FunctionInnards << " (" << NameSoFar << ") (";
286 for (FunctionType::param_iterator I = MTy->param_begin(),
287 E = MTy->param_end(); I != E; ++I) {
288 if (I != MTy->param_begin())
289 FunctionInnards << ", ";
290 printType(FunctionInnards, *I, "");
292 if (MTy->isVarArg()) {
293 if (MTy->getNumParams())
294 FunctionInnards << ", ...";
295 } else if (!MTy->getNumParams()) {
296 FunctionInnards << "void";
298 FunctionInnards << ")";
299 std::string tstr = FunctionInnards.str();
300 printType(Out, MTy->getReturnType(), tstr);
303 case Type::StructTyID: {
304 const StructType *STy = cast<StructType>(Ty);
305 Out << NameSoFar + " {\n";
307 for (StructType::element_iterator I = STy->element_begin(),
308 E = STy->element_end(); I != E; ++I) {
310 printType(Out, *I, "field" + utostr(Idx++));
316 case Type::PointerTyID: {
317 const PointerType *PTy = cast<PointerType>(Ty);
318 std::string ptrName = "*" + NameSoFar;
320 if (isa<ArrayType>(PTy->getElementType()))
321 ptrName = "(" + ptrName + ")";
323 return printType(Out, PTy->getElementType(), ptrName);
326 case Type::ArrayTyID: {
327 const ArrayType *ATy = cast<ArrayType>(Ty);
328 unsigned NumElements = ATy->getNumElements();
329 return printType(Out, ATy->getElementType(),
330 NameSoFar + "[" + utostr(NumElements) + "]");
333 case Type::OpaqueTyID: {
334 static int Count = 0;
335 std::string TyName = "struct opaque_" + itostr(Count++);
336 assert(TypeNames.find(Ty) == TypeNames.end());
337 TypeNames[Ty] = TyName;
338 return Out << TyName << " " << NameSoFar;
341 assert(0 && "Unhandled case in getTypeProps!");
348 void CWriter::printConstantArray(ConstantArray *CPA) {
350 // As a special case, print the array as a string if it is an array of
351 // ubytes or an array of sbytes with positive values.
353 const Type *ETy = CPA->getType()->getElementType();
354 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
356 // Make sure the last character is a null char, as automatically added by C
357 if (isString && (CPA->getNumOperands() == 0 ||
358 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
363 // Keep track of whether the last number was a hexadecimal escape
364 bool LastWasHex = false;
366 // Do not include the last character, which we know is null
367 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
368 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
370 // Print it out literally if it is a printable character. The only thing
371 // to be careful about is when the last letter output was a hex escape
372 // code, in which case we have to be careful not to print out hex digits
373 // explicitly (the C compiler thinks it is a continuation of the previous
374 // character, sheesh...)
376 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
378 if (C == '"' || C == '\\')
385 case '\n': Out << "\\n"; break;
386 case '\t': Out << "\\t"; break;
387 case '\r': Out << "\\r"; break;
388 case '\v': Out << "\\v"; break;
389 case '\a': Out << "\\a"; break;
390 case '\"': Out << "\\\""; break;
391 case '\'': Out << "\\\'"; break;
394 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
395 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
404 if (CPA->getNumOperands()) {
406 printConstant(cast<Constant>(CPA->getOperand(0)));
407 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
409 printConstant(cast<Constant>(CPA->getOperand(i)));
416 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
417 // textually as a double (rather than as a reference to a stack-allocated
418 // variable). We decide this by converting CFP to a string and back into a
419 // double, and then checking whether the conversion results in a bit-equal
420 // double to the original value of CFP. This depends on us and the target C
421 // compiler agreeing on the conversion process (which is pretty likely since we
422 // only deal in IEEE FP).
424 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
427 sprintf(Buffer, "%a", CFP->getValue());
429 if (!strncmp(Buffer, "0x", 2) ||
430 !strncmp(Buffer, "-0x", 3) ||
431 !strncmp(Buffer, "+0x", 3))
432 return atof(Buffer) == CFP->getValue();
435 std::string StrVal = ftostr(CFP->getValue());
437 while (StrVal[0] == ' ')
438 StrVal.erase(StrVal.begin());
440 // Check to make sure that the stringized number is not some string like "Inf"
441 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
442 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
443 ((StrVal[0] == '-' || StrVal[0] == '+') &&
444 (StrVal[1] >= '0' && StrVal[1] <= '9')))
445 // Reparse stringized version!
446 return atof(StrVal.c_str()) == CFP->getValue();
451 // printConstant - The LLVM Constant to C Constant converter.
452 void CWriter::printConstant(Constant *CPV) {
453 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
454 switch (CE->getOpcode()) {
455 case Instruction::Cast:
457 printType(Out, CPV->getType());
459 printConstant(CE->getOperand(0));
463 case Instruction::GetElementPtr:
465 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
469 case Instruction::Select:
471 printConstant(CE->getOperand(0));
473 printConstant(CE->getOperand(1));
475 printConstant(CE->getOperand(2));
478 case Instruction::Add:
479 case Instruction::Sub:
480 case Instruction::Mul:
481 case Instruction::Div:
482 case Instruction::Rem:
483 case Instruction::SetEQ:
484 case Instruction::SetNE:
485 case Instruction::SetLT:
486 case Instruction::SetLE:
487 case Instruction::SetGT:
488 case Instruction::SetGE:
489 case Instruction::Shl:
490 case Instruction::Shr:
492 printConstant(CE->getOperand(0));
493 switch (CE->getOpcode()) {
494 case Instruction::Add: Out << " + "; break;
495 case Instruction::Sub: Out << " - "; break;
496 case Instruction::Mul: Out << " * "; break;
497 case Instruction::Div: Out << " / "; break;
498 case Instruction::Rem: Out << " % "; break;
499 case Instruction::SetEQ: Out << " == "; break;
500 case Instruction::SetNE: Out << " != "; break;
501 case Instruction::SetLT: Out << " < "; break;
502 case Instruction::SetLE: Out << " <= "; break;
503 case Instruction::SetGT: Out << " > "; break;
504 case Instruction::SetGE: Out << " >= "; break;
505 case Instruction::Shl: Out << " << "; break;
506 case Instruction::Shr: Out << " >> "; break;
507 default: assert(0 && "Illegal opcode here!");
509 printConstant(CE->getOperand(1));
514 std::cerr << "CWriter Error: Unhandled constant expression: "
520 switch (CPV->getType()->getPrimitiveID()) {
522 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
523 case Type::SByteTyID:
524 case Type::ShortTyID:
525 Out << cast<ConstantSInt>(CPV)->getValue(); break;
527 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
528 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
530 Out << cast<ConstantSInt>(CPV)->getValue();
534 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
536 case Type::UByteTyID:
537 case Type::UShortTyID:
538 Out << cast<ConstantUInt>(CPV)->getValue(); break;
540 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
541 case Type::ULongTyID:
542 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
544 case Type::FloatTyID:
545 case Type::DoubleTyID: {
546 ConstantFP *FPC = cast<ConstantFP>(CPV);
547 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
548 if (I != FPConstantMap.end()) {
549 // Because of FP precision problems we must load from a stack allocated
550 // value that holds the value in hex.
551 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
552 << "*)&FPConstant" << I->second << ")";
555 // Print out the constant as a floating point number.
557 sprintf(Buffer, "%a", FPC->getValue());
558 Out << Buffer << " /*" << FPC->getValue() << "*/ ";
560 Out << ftostr(FPC->getValue());
566 case Type::ArrayTyID:
567 if (isa<ConstantAggregateZero>(CPV)) {
568 const ArrayType *AT = cast<ArrayType>(CPV->getType());
570 if (AT->getNumElements()) {
572 Constant *CZ = Constant::getNullValue(AT->getElementType());
574 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
581 printConstantArray(cast<ConstantArray>(CPV));
585 case Type::StructTyID:
586 if (isa<ConstantAggregateZero>(CPV)) {
587 const StructType *ST = cast<StructType>(CPV->getType());
589 if (ST->getNumElements()) {
591 printConstant(Constant::getNullValue(ST->getElementType(0)));
592 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
594 printConstant(Constant::getNullValue(ST->getElementType(i)));
600 if (CPV->getNumOperands()) {
602 printConstant(cast<Constant>(CPV->getOperand(0)));
603 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
605 printConstant(cast<Constant>(CPV->getOperand(i)));
612 case Type::PointerTyID:
613 if (isa<ConstantPointerNull>(CPV)) {
615 printType(Out, CPV->getType());
616 Out << ")/*NULL*/0)";
618 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
619 writeOperand(CPR->getValue());
624 std::cerr << "Unknown constant type: " << CPV << "\n";
629 void CWriter::writeOperandInternal(Value *Operand) {
630 if (Instruction *I = dyn_cast<Instruction>(Operand))
631 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
632 // Should we inline this instruction to build a tree?
639 if (Constant *CPV = dyn_cast<Constant>(Operand)) {
642 Out << Mang->getValueName(Operand);
646 void CWriter::writeOperand(Value *Operand) {
647 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
648 Out << "(&"; // Global variables are references as their addresses by llvm
650 writeOperandInternal(Operand);
652 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
656 // generateCompilerSpecificCode - This is where we add conditional compilation
657 // directives to cater to specific compilers as need be.
659 static void generateCompilerSpecificCode(std::ostream& Out) {
660 // Alloca is hard to get, and we don't want to include stdlib.h here...
661 Out << "/* get a declaration for alloca */\n"
663 << "extern void *__builtin_alloca(unsigned long);\n"
664 << "#define alloca(x) __builtin_alloca(x)\n"
666 << "#ifndef __FreeBSD__\n"
667 << "#include <alloca.h>\n"
671 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
672 // If we aren't being compiled with GCC, just drop these attributes.
673 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
674 << "#define __attribute__(X)\n"
678 // At some point, we should support "external weak" vs. "weak" linkages.
679 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
680 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
681 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
682 << "#elif defined(__GNUC__)\n"
683 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
685 << "#define __EXTERNAL_WEAK__\n"
689 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
690 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
691 << "#define __ATTRIBUTE_WEAK__\n"
692 << "#elif defined(__GNUC__)\n"
693 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
695 << "#define __ATTRIBUTE_WEAK__\n"
699 bool CWriter::doInitialization(Module &M) {
705 // Ensure that all structure types have names...
706 Mang = new Mangler(M);
708 // get declaration for alloca
709 Out << "/* Provide Declarations */\n";
710 Out << "#include <stdarg.h>\n"; // Varargs support
711 Out << "#include <setjmp.h>\n"; // Unwind support
712 generateCompilerSpecificCode(Out);
714 // Provide a definition for `bool' if not compiling with a C++ compiler.
716 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
718 << "\n\n/* Support for floating point constants */\n"
719 << "typedef unsigned long long ConstantDoubleTy;\n"
720 << "typedef unsigned int ConstantFloatTy;\n"
722 << "\n\n/* Global Declarations */\n";
724 // First output all the declarations for the program, because C requires
725 // Functions & globals to be declared before they are used.
728 // Loop over the symbol table, emitting all named constants...
729 printModuleTypes(M.getSymbolTable());
731 // Global variable declarations...
733 Out << "\n/* External Global Variable Declarations */\n";
734 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
735 if (I->hasExternalLinkage()) {
737 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
743 // Function declarations
745 Out << "\n/* Function Declarations */\n";
746 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
747 // Don't print declarations for intrinsic functions.
748 if (!I->getIntrinsicID() &&
749 I->getName() != "setjmp" && I->getName() != "longjmp") {
750 printFunctionSignature(I, true);
751 if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
752 if (I->hasLinkOnceLinkage()) Out << " __ATTRIBUTE_WEAK__";
758 // Output the global variable declarations
760 Out << "\n\n/* Global Variable Declarations */\n";
761 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
762 if (!I->isExternal()) {
764 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
766 if (I->hasLinkOnceLinkage())
767 Out << " __attribute__((common))";
768 else if (I->hasWeakLinkage())
769 Out << " __ATTRIBUTE_WEAK__";
774 // Output the global variable definitions and contents...
776 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
777 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
778 if (!I->isExternal()) {
779 if (I->hasInternalLinkage())
781 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
782 if (I->hasLinkOnceLinkage())
783 Out << " __attribute__((common))";
784 else if (I->hasWeakLinkage())
785 Out << " __ATTRIBUTE_WEAK__";
787 // If the initializer is not null, emit the initializer. If it is null,
788 // we try to avoid emitting large amounts of zeros. The problem with
789 // this, however, occurs when the variable has weak linkage. In this
790 // case, the assembler will complain about the variable being both weak
791 // and common, so we disable this optimization.
792 if (!I->getInitializer()->isNullValue()) {
794 writeOperand(I->getInitializer());
795 } else if (I->hasWeakLinkage()) {
796 // We have to specify an initializer, but it doesn't have to be
797 // complete. If the value is an aggregate, print out { 0 }, and let
798 // the compiler figure out the rest of the zeros.
800 if (isa<StructType>(I->getInitializer()->getType()) ||
801 isa<ArrayType>(I->getInitializer()->getType())) {
804 // Just print it out normally.
805 writeOperand(I->getInitializer());
813 Out << "\n\n/* Function Bodies */\n";
818 /// Output all floating point constants that cannot be printed accurately...
819 void CWriter::printFloatingPointConstants(Function &F) {
830 // Scan the module for floating point constants. If any FP constant is used
831 // in the function, we want to redirect it here so that we do not depend on
832 // the precision of the printed form, unless the printed form preserves
835 static unsigned FPCounter = 0;
836 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
838 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
839 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
840 !FPConstantMap.count(FPC)) {
841 double Val = FPC->getValue();
843 FPConstantMap[FPC] = FPCounter; // Number the FP constants
845 if (FPC->getType() == Type::DoubleTy) {
847 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
848 << " = 0x" << std::hex << DBLUnion.U << std::dec
849 << "ULL; /* " << Val << " */\n";
850 } else if (FPC->getType() == Type::FloatTy) {
852 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
853 << " = 0x" << std::hex << FLTUnion.U << std::dec
854 << "U; /* " << Val << " */\n";
856 assert(0 && "Unknown float type!");
863 /// printSymbolTable - Run through symbol table looking for type names. If a
864 /// type name is found, emit it's declaration...
866 void CWriter::printModuleTypes(const SymbolTable &ST) {
867 // If there are no type names, exit early.
868 if (ST.find(Type::TypeTy) == ST.end())
871 // We are only interested in the type plane of the symbol table...
872 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
873 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
875 // Print out forward declarations for structure types before anything else!
876 Out << "/* Structure forward decls */\n";
877 for (; I != End; ++I)
878 if (const Type *STy = dyn_cast<StructType>(I->second)) {
879 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
880 Out << Name << ";\n";
881 TypeNames.insert(std::make_pair(STy, Name));
886 // Now we can print out typedefs...
887 Out << "/* Typedefs */\n";
888 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
889 const Type *Ty = cast<Type>(I->second);
890 std::string Name = "l_" + Mangler::makeNameProper(I->first);
892 printType(Out, Ty, Name);
898 // Keep track of which structures have been printed so far...
899 std::set<const StructType *> StructPrinted;
901 // Loop over all structures then push them into the stack so they are
902 // printed in the correct order.
904 Out << "/* Structure contents */\n";
905 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
906 if (const StructType *STy = dyn_cast<StructType>(I->second))
907 // Only print out used types!
908 printContainedStructs(STy, StructPrinted);
911 // Push the struct onto the stack and recursively push all structs
912 // this one depends on.
913 void CWriter::printContainedStructs(const Type *Ty,
914 std::set<const StructType*> &StructPrinted){
915 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
916 //Check to see if we have already printed this struct
917 if (StructPrinted.count(STy) == 0) {
918 // Print all contained types first...
919 for (StructType::element_iterator I = STy->element_begin(),
920 E = STy->element_end(); I != E; ++I) {
921 const Type *Ty1 = I->get();
922 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
923 printContainedStructs(*I, StructPrinted);
926 //Print structure type out..
927 StructPrinted.insert(STy);
928 std::string Name = TypeNames[STy];
929 printType(Out, STy, Name, true);
933 // If it is an array, check contained types and continue
934 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
935 const Type *Ty1 = ATy->getElementType();
936 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
937 printContainedStructs(Ty1, StructPrinted);
942 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
943 if (F->hasInternalLinkage()) Out << "static ";
945 // Loop over the arguments, printing them...
946 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
948 std::stringstream FunctionInnards;
950 // Print out the name...
951 FunctionInnards << Mang->getValueName(F) << "(";
953 if (!F->isExternal()) {
956 if (F->abegin()->hasName() || !Prototype)
957 ArgName = Mang->getValueName(F->abegin());
958 printType(FunctionInnards, F->afront().getType(), ArgName);
959 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
961 FunctionInnards << ", ";
962 if (I->hasName() || !Prototype)
963 ArgName = Mang->getValueName(I);
966 printType(FunctionInnards, I->getType(), ArgName);
970 // Loop over the arguments, printing them...
971 for (FunctionType::param_iterator I = FT->param_begin(),
972 E = FT->param_end(); I != E; ++I) {
973 if (I != FT->param_begin()) FunctionInnards << ", ";
974 printType(FunctionInnards, *I);
978 // Finish printing arguments... if this is a vararg function, print the ...,
979 // unless there are no known types, in which case, we just emit ().
981 if (FT->isVarArg() && FT->getNumParams()) {
982 if (FT->getNumParams()) FunctionInnards << ", ";
983 FunctionInnards << "..."; // Output varargs portion of signature!
984 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
985 FunctionInnards << "void"; // ret() -> ret(void) in C.
987 FunctionInnards << ")";
988 // Print out the return type and the entire signature for that matter
989 printType(Out, F->getReturnType(), FunctionInnards.str());
992 void CWriter::printFunction(Function &F) {
993 printFunctionSignature(&F, false);
996 // print local variable information for the function
997 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
998 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1000 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1001 Out << "; /* Address exposed local */\n";
1002 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1004 printType(Out, I->getType(), Mang->getValueName(&*I));
1007 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1009 printType(Out, I->getType(),
1010 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1017 // print the basic blocks
1018 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1019 if (Loop *L = LI->getLoopFor(BB)) {
1020 if (L->getHeader() == BB && L->getParentLoop() == 0)
1023 printBasicBlock(BB);
1030 void CWriter::printLoop(Loop *L) {
1031 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1032 << "' to make GCC happy */\n";
1033 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1034 BasicBlock *BB = L->getBlocks()[i];
1035 Loop *BBLoop = LI->getLoopFor(BB);
1037 printBasicBlock(BB);
1038 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1041 Out << " } while (1); /* end of syntactic loop '"
1042 << L->getHeader()->getName() << "' */\n";
1045 void CWriter::printBasicBlock(BasicBlock *BB) {
1047 // Don't print the label for the basic block if there are no uses, or if
1048 // the only terminator use is the predecessor basic block's terminator.
1049 // We have to scan the use list because PHI nodes use basic blocks too but
1050 // do not require a label to be generated.
1052 bool NeedsLabel = false;
1053 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1054 if (isGotoCodeNecessary(*PI, BB)) {
1059 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1061 // Output all of the instructions in the basic block...
1062 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1064 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1065 if (II->getType() != Type::VoidTy)
1074 // Don't emit prefix or suffix for the terminator...
1075 visit(*BB->getTerminator());
1079 // Specific Instruction type classes... note that all of the casts are
1080 // necessary because we use the instruction classes as opaque types...
1082 void CWriter::visitReturnInst(ReturnInst &I) {
1083 // Don't output a void return if this is the last basic block in the function
1084 if (I.getNumOperands() == 0 &&
1085 &*--I.getParent()->getParent()->end() == I.getParent() &&
1086 !I.getParent()->size() == 1) {
1091 if (I.getNumOperands()) {
1093 writeOperand(I.getOperand(0));
1098 void CWriter::visitSwitchInst(SwitchInst &SI) {
1099 printPHICopiesForSuccessors(SI.getParent(), 0);
1102 writeOperand(SI.getOperand(0));
1103 Out << ") {\n default:\n";
1104 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1106 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1108 writeOperand(SI.getOperand(i));
1110 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1111 printBranchToBlock(SI.getParent(), Succ, 2);
1112 if (Succ == SI.getParent()->getNext())
1118 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1119 /// FIXME: This should be reenabled, but loop reordering safe!!
1122 if (From->getNext() != To) // Not the direct successor, we need a goto
1125 //isa<SwitchInst>(From->getTerminator())
1128 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1133 void CWriter::printPHICopiesForSuccessors(BasicBlock *CurBlock,
1135 for (succ_iterator SI = succ_begin(CurBlock), E = succ_end(CurBlock);
1137 for (BasicBlock::iterator I = SI->begin();
1138 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1139 // now we have to do the printing
1140 Out << std::string(Indent, ' ');
1141 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1142 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBlock)));
1143 Out << "; /* for PHI node */\n";
1148 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1150 if (isGotoCodeNecessary(CurBB, Succ)) {
1151 Out << std::string(Indent, ' ') << " goto ";
1157 // Branch instruction printing - Avoid printing out a branch to a basic block
1158 // that immediately succeeds the current one.
1160 void CWriter::visitBranchInst(BranchInst &I) {
1161 printPHICopiesForSuccessors(I.getParent(), 0);
1163 if (I.isConditional()) {
1164 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1166 writeOperand(I.getCondition());
1169 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1171 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1172 Out << " } else {\n";
1173 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1176 // First goto not necessary, assume second one is...
1178 writeOperand(I.getCondition());
1181 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1186 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1191 // PHI nodes get copied into temporary values at the end of predecessor basic
1192 // blocks. We now need to copy these temporary values into the REAL value for
1194 void CWriter::visitPHINode(PHINode &I) {
1196 Out << "__PHI_TEMPORARY";
1200 void CWriter::visitBinaryOperator(Instruction &I) {
1201 // binary instructions, shift instructions, setCond instructions.
1202 assert(!isa<PointerType>(I.getType()));
1204 // We must cast the results of binary operations which might be promoted.
1205 bool needsCast = false;
1206 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1207 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1208 || (I.getType() == Type::FloatTy)) {
1211 printType(Out, I.getType());
1215 writeOperand(I.getOperand(0));
1217 switch (I.getOpcode()) {
1218 case Instruction::Add: Out << " + "; break;
1219 case Instruction::Sub: Out << " - "; break;
1220 case Instruction::Mul: Out << "*"; break;
1221 case Instruction::Div: Out << "/"; break;
1222 case Instruction::Rem: Out << "%"; break;
1223 case Instruction::And: Out << " & "; break;
1224 case Instruction::Or: Out << " | "; break;
1225 case Instruction::Xor: Out << " ^ "; break;
1226 case Instruction::SetEQ: Out << " == "; break;
1227 case Instruction::SetNE: Out << " != "; break;
1228 case Instruction::SetLE: Out << " <= "; break;
1229 case Instruction::SetGE: Out << " >= "; break;
1230 case Instruction::SetLT: Out << " < "; break;
1231 case Instruction::SetGT: Out << " > "; break;
1232 case Instruction::Shl : Out << " << "; break;
1233 case Instruction::Shr : Out << " >> "; break;
1234 default: std::cerr << "Invalid operator type!" << I; abort();
1237 writeOperand(I.getOperand(1));
1244 void CWriter::visitCastInst(CastInst &I) {
1245 if (I.getType() == Type::BoolTy) {
1247 writeOperand(I.getOperand(0));
1252 printType(Out, I.getType());
1254 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1255 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1256 // Avoid "cast to pointer from integer of different size" warnings
1260 writeOperand(I.getOperand(0));
1263 void CWriter::visitSelectInst(SelectInst &I) {
1265 writeOperand(I.getCondition());
1267 writeOperand(I.getTrueValue());
1269 writeOperand(I.getFalseValue());
1274 void CWriter::lowerIntrinsics(Function &F) {
1275 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1276 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1277 if (CallInst *CI = dyn_cast<CallInst>(I++))
1278 if (Function *F = CI->getCalledFunction())
1279 switch (F->getIntrinsicID()) {
1280 case Intrinsic::not_intrinsic:
1281 case Intrinsic::vastart:
1282 case Intrinsic::vacopy:
1283 case Intrinsic::vaend:
1284 case Intrinsic::returnaddress:
1285 case Intrinsic::frameaddress:
1286 case Intrinsic::setjmp:
1287 case Intrinsic::longjmp:
1288 // We directly implement these intrinsics
1291 // All other intrinsic calls we must lower.
1292 Instruction *Before = CI->getPrev();
1293 IL.LowerIntrinsicCall(CI);
1294 if (Before) { // Move iterator to instruction after call
1304 void CWriter::visitCallInst(CallInst &I) {
1305 // Handle intrinsic function calls first...
1306 if (Function *F = I.getCalledFunction())
1307 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1309 default: assert(0 && "Unknown LLVM intrinsic!");
1310 case Intrinsic::vastart:
1313 Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1314 // Output the last argument to the enclosing function...
1315 if (I.getParent()->getParent()->aempty()) {
1316 std::cerr << "The C backend does not currently support zero "
1317 << "argument varargs functions, such as '"
1318 << I.getParent()->getParent()->getName() << "'!\n";
1321 writeOperand(&I.getParent()->getParent()->aback());
1324 case Intrinsic::vaend:
1325 Out << "va_end(*(va_list*)&";
1326 writeOperand(I.getOperand(1));
1329 case Intrinsic::vacopy:
1331 Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1332 Out << "*(va_list*)&";
1333 writeOperand(I.getOperand(1));
1336 case Intrinsic::returnaddress:
1337 Out << "__builtin_return_address(";
1338 writeOperand(I.getOperand(1));
1341 case Intrinsic::frameaddress:
1342 Out << "__builtin_frame_address(";
1343 writeOperand(I.getOperand(1));
1346 case Intrinsic::setjmp:
1347 Out << "setjmp(*(jmp_buf*)";
1348 writeOperand(I.getOperand(1));
1351 case Intrinsic::longjmp:
1352 Out << "longjmp(*(jmp_buf*)";
1353 writeOperand(I.getOperand(1));
1355 writeOperand(I.getOperand(2));
1363 void CWriter::visitCallSite(CallSite CS) {
1364 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1365 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1366 const Type *RetTy = FTy->getReturnType();
1368 writeOperand(CS.getCalledValue());
1371 if (CS.arg_begin() != CS.arg_end()) {
1372 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1375 for (++AI; AI != AE; ++AI) {
1383 void CWriter::visitMallocInst(MallocInst &I) {
1384 assert(0 && "lowerallocations pass didn't work!");
1387 void CWriter::visitAllocaInst(AllocaInst &I) {
1389 printType(Out, I.getType());
1390 Out << ") alloca(sizeof(";
1391 printType(Out, I.getType()->getElementType());
1393 if (I.isArrayAllocation()) {
1395 writeOperand(I.getOperand(0));
1400 void CWriter::visitFreeInst(FreeInst &I) {
1401 assert(0 && "lowerallocations pass didn't work!");
1404 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1405 gep_type_iterator E) {
1406 bool HasImplicitAddress = false;
1407 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1408 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1409 HasImplicitAddress = true;
1410 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1411 HasImplicitAddress = true;
1412 Ptr = CPR->getValue(); // Get to the global...
1413 } else if (isDirectAlloca(Ptr)) {
1414 HasImplicitAddress = true;
1418 if (!HasImplicitAddress)
1419 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1421 writeOperandInternal(Ptr);
1425 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1426 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1429 writeOperandInternal(Ptr);
1431 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1433 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1436 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1437 "Can only have implicit address with direct accessing");
1439 if (HasImplicitAddress) {
1441 } else if (CI && CI->isNullValue()) {
1442 gep_type_iterator TmpI = I; ++TmpI;
1444 // Print out the -> operator if possible...
1445 if (TmpI != E && isa<StructType>(*TmpI)) {
1446 Out << (HasImplicitAddress ? "." : "->");
1447 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1453 if (isa<StructType>(*I)) {
1454 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1457 writeOperand(I.getOperand());
1462 void CWriter::visitLoadInst(LoadInst &I) {
1464 writeOperand(I.getOperand(0));
1467 void CWriter::visitStoreInst(StoreInst &I) {
1469 writeOperand(I.getPointerOperand());
1471 writeOperand(I.getOperand(0));
1474 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1476 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1480 void CWriter::visitVANextInst(VANextInst &I) {
1481 Out << Mang->getValueName(I.getOperand(0));
1482 Out << "; va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1483 printType(Out, I.getArgType());
1487 void CWriter::visitVAArgInst(VAArgInst &I) {
1489 Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1490 writeOperand(I.getOperand(0));
1491 Out << ");\n " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1492 printType(Out, I.getType());
1493 Out << ");\n va_end(Tmp); }";
1496 //===----------------------------------------------------------------------===//
1497 // External Interface declaration
1498 //===----------------------------------------------------------------------===//
1500 bool CTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &o) {
1501 PM.add(createLowerAllocationsPass());
1502 PM.add(createLowerInvokePass());
1503 PM.add(new CBackendNameAllUsedStructs());
1504 PM.add(new CWriter(o, getIntrinsicLowering()));
1508 TargetMachine *llvm::allocateCTargetMachine(const Module &M,
1509 IntrinsicLowering *IL) {
1510 return new CTargetMachine(M, IL);