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/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/PassManager.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Analysis/ConstantsScanner.h"
25 #include "llvm/Analysis/FindUsedTypes.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Target/TargetMachineRegistry.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 "llvm/Support/MathExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Config/config.h"
47 // Register the target.
48 RegisterTarget<CTargetMachine> X("c", " C backend");
50 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
51 /// any unnamed structure types that are used by the program, and merges
52 /// external functions with the same name.
54 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
55 void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<FindUsedTypes>();
59 virtual const char *getPassName() const {
60 return "C backend type canonicalizer";
63 virtual bool runOnModule(Module &M);
66 /// CWriter - This class is the main chunk of code that converts an LLVM
67 /// module to a C translation unit.
68 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
70 IntrinsicLowering &IL;
73 const Module *TheModule;
74 std::map<const Type *, std::string> TypeNames;
76 std::map<const ConstantFP *, unsigned> FPConstantMap;
78 CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
80 virtual const char *getPassName() const { return "C backend"; }
82 void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequired<LoopInfo>();
87 virtual bool doInitialization(Module &M);
89 bool runOnFunction(Function &F) {
90 LI = &getAnalysis<LoopInfo>();
92 // Get rid of intrinsics we can't handle.
95 // Output all floating point constants that cannot be printed accurately.
96 printFloatingPointConstants(F);
98 // Ensure that no local symbols conflict with global symbols.
99 F.renameLocalSymbols();
102 FPConstantMap.clear();
106 virtual bool doFinalization(Module &M) {
113 std::ostream &printType(std::ostream &Out, const Type *Ty,
114 const std::string &VariableName = "",
115 bool IgnoreName = false);
117 void writeOperand(Value *Operand);
118 void writeOperandInternal(Value *Operand);
121 void lowerIntrinsics(Function &F);
123 void printModule(Module *M);
124 void printModuleTypes(const SymbolTable &ST);
125 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
126 void printFloatingPointConstants(Function &F);
127 void printFunctionSignature(const Function *F, bool Prototype);
129 void printFunction(Function &);
130 void printBasicBlock(BasicBlock *BB);
131 void printLoop(Loop *L);
133 void printConstant(Constant *CPV);
134 void printConstantArray(ConstantArray *CPA);
135 void printConstantPacked(ConstantPacked *CP);
137 // isInlinableInst - Attempt to inline instructions into their uses to build
138 // trees as much as possible. To do this, we have to consistently decide
139 // what is acceptable to inline, so that variable declarations don't get
140 // printed and an extra copy of the expr is not emitted.
142 static bool isInlinableInst(const Instruction &I) {
143 // Always inline setcc instructions, even if they are shared by multiple
144 // expressions. GCC generates horrible code if we don't.
145 if (isa<SetCondInst>(I)) return true;
147 // Must be an expression, must be used exactly once. If it is dead, we
148 // emit it inline where it would go.
149 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
150 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
151 isa<LoadInst>(I) || isa<VAArgInst>(I))
152 // Don't inline a load across a store or other bad things!
155 // Only inline instruction it it's use is in the same BB as the inst.
156 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
159 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
160 // variables which are accessed with the & operator. This causes GCC to
161 // generate significantly better code than to emit alloca calls directly.
163 static const AllocaInst *isDirectAlloca(const Value *V) {
164 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
165 if (!AI) return false;
166 if (AI->isArrayAllocation())
167 return 0; // FIXME: we can also inline fixed size array allocas!
168 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
173 // Instruction visitation functions
174 friend class InstVisitor<CWriter>;
176 void visitReturnInst(ReturnInst &I);
177 void visitBranchInst(BranchInst &I);
178 void visitSwitchInst(SwitchInst &I);
179 void visitInvokeInst(InvokeInst &I) {
180 assert(0 && "Lowerinvoke pass didn't work!");
183 void visitUnwindInst(UnwindInst &I) {
184 assert(0 && "Lowerinvoke pass didn't work!");
186 void visitUnreachableInst(UnreachableInst &I);
188 void visitPHINode(PHINode &I);
189 void visitBinaryOperator(Instruction &I);
191 void visitCastInst (CastInst &I);
192 void visitSelectInst(SelectInst &I);
193 void visitCallInst (CallInst &I);
194 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
196 void visitMallocInst(MallocInst &I);
197 void visitAllocaInst(AllocaInst &I);
198 void visitFreeInst (FreeInst &I);
199 void visitLoadInst (LoadInst &I);
200 void visitStoreInst (StoreInst &I);
201 void visitGetElementPtrInst(GetElementPtrInst &I);
202 void visitVAArgInst (VAArgInst &I);
204 void visitInstruction(Instruction &I) {
205 std::cerr << "C Writer does not know about " << I;
209 void outputLValue(Instruction *I) {
210 Out << " " << Mang->getValueName(I) << " = ";
213 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
214 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
215 BasicBlock *Successor, unsigned Indent);
216 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
218 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
219 gep_type_iterator E);
223 /// This method inserts names for any unnamed structure types that are used by
224 /// the program, and removes names from structure types that are not used by the
227 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
228 // Get a set of types that are used by the program...
229 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
231 // Loop over the module symbol table, removing types from UT that are
232 // already named, and removing names for types that are not used.
234 SymbolTable &MST = M.getSymbolTable();
235 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
237 SymbolTable::type_iterator I = TI++;
239 // If this is not used, remove it from the symbol table.
240 std::set<const Type *>::iterator UTI = UT.find(I->second);
244 UT.erase(UTI); // Only keep one name for this type.
247 // UT now contains types that are not named. Loop over it, naming
250 bool Changed = false;
251 unsigned RenameCounter = 0;
252 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
254 if (const StructType *ST = dyn_cast<StructType>(*I)) {
255 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
261 // Loop over all external functions and globals. If we have two with
262 // identical names, merge them.
263 // FIXME: This code should disappear when we don't allow values with the same
264 // names when they have different types!
265 std::map<std::string, GlobalValue*> ExtSymbols;
266 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
268 if (GV->isExternal() && GV->hasName()) {
269 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
270 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
272 // Found a conflict, replace this global with the previous one.
273 GlobalValue *OldGV = X.first->second;
274 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
275 GV->eraseFromParent();
280 // Do the same for globals.
281 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
283 GlobalVariable *GV = I++;
284 if (GV->isExternal() && GV->hasName()) {
285 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
286 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
288 // Found a conflict, replace this global with the previous one.
289 GlobalValue *OldGV = X.first->second;
290 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
291 GV->eraseFromParent();
301 // Pass the Type* and the variable name and this prints out the variable
304 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
305 const std::string &NameSoFar,
307 if (Ty->isPrimitiveType())
308 switch (Ty->getTypeID()) {
309 case Type::VoidTyID: return Out << "void " << NameSoFar;
310 case Type::BoolTyID: return Out << "bool " << NameSoFar;
311 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
312 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
313 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
314 case Type::ShortTyID: return Out << "short " << NameSoFar;
315 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
316 case Type::IntTyID: return Out << "int " << NameSoFar;
317 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
318 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
319 case Type::FloatTyID: return Out << "float " << NameSoFar;
320 case Type::DoubleTyID: return Out << "double " << NameSoFar;
322 std::cerr << "Unknown primitive type: " << *Ty << "\n";
326 // Check to see if the type is named.
327 if (!IgnoreName || isa<OpaqueType>(Ty)) {
328 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
329 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
332 switch (Ty->getTypeID()) {
333 case Type::FunctionTyID: {
334 const FunctionType *MTy = cast<FunctionType>(Ty);
335 std::stringstream FunctionInnards;
336 FunctionInnards << " (" << NameSoFar << ") (";
337 for (FunctionType::param_iterator I = MTy->param_begin(),
338 E = MTy->param_end(); I != E; ++I) {
339 if (I != MTy->param_begin())
340 FunctionInnards << ", ";
341 printType(FunctionInnards, *I, "");
343 if (MTy->isVarArg()) {
344 if (MTy->getNumParams())
345 FunctionInnards << ", ...";
346 } else if (!MTy->getNumParams()) {
347 FunctionInnards << "void";
349 FunctionInnards << ')';
350 std::string tstr = FunctionInnards.str();
351 printType(Out, MTy->getReturnType(), tstr);
354 case Type::StructTyID: {
355 const StructType *STy = cast<StructType>(Ty);
356 Out << NameSoFar + " {\n";
358 for (StructType::element_iterator I = STy->element_begin(),
359 E = STy->element_end(); I != E; ++I) {
361 printType(Out, *I, "field" + utostr(Idx++));
367 case Type::PointerTyID: {
368 const PointerType *PTy = cast<PointerType>(Ty);
369 std::string ptrName = "*" + NameSoFar;
371 if (isa<ArrayType>(PTy->getElementType()) ||
372 isa<PackedType>(PTy->getElementType()))
373 ptrName = "(" + ptrName + ")";
375 return printType(Out, PTy->getElementType(), ptrName);
378 case Type::ArrayTyID: {
379 const ArrayType *ATy = cast<ArrayType>(Ty);
380 unsigned NumElements = ATy->getNumElements();
381 if (NumElements == 0) NumElements = 1;
382 return printType(Out, ATy->getElementType(),
383 NameSoFar + "[" + utostr(NumElements) + "]");
386 case Type::PackedTyID: {
387 const PackedType *PTy = cast<PackedType>(Ty);
388 unsigned NumElements = PTy->getNumElements();
389 if (NumElements == 0) NumElements = 1;
390 return printType(Out, PTy->getElementType(),
391 NameSoFar + "[" + utostr(NumElements) + "]");
394 case Type::OpaqueTyID: {
395 static int Count = 0;
396 std::string TyName = "struct opaque_" + itostr(Count++);
397 assert(TypeNames.find(Ty) == TypeNames.end());
398 TypeNames[Ty] = TyName;
399 return Out << TyName << ' ' << NameSoFar;
402 assert(0 && "Unhandled case in getTypeProps!");
409 void CWriter::printConstantArray(ConstantArray *CPA) {
411 // As a special case, print the array as a string if it is an array of
412 // ubytes or an array of sbytes with positive values.
414 const Type *ETy = CPA->getType()->getElementType();
415 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
417 // Make sure the last character is a null char, as automatically added by C
418 if (isString && (CPA->getNumOperands() == 0 ||
419 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
424 // Keep track of whether the last number was a hexadecimal escape
425 bool LastWasHex = false;
427 // Do not include the last character, which we know is null
428 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
429 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
431 // Print it out literally if it is a printable character. The only thing
432 // to be careful about is when the last letter output was a hex escape
433 // code, in which case we have to be careful not to print out hex digits
434 // explicitly (the C compiler thinks it is a continuation of the previous
435 // character, sheesh...)
437 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
439 if (C == '"' || C == '\\')
446 case '\n': Out << "\\n"; break;
447 case '\t': Out << "\\t"; break;
448 case '\r': Out << "\\r"; break;
449 case '\v': Out << "\\v"; break;
450 case '\a': Out << "\\a"; break;
451 case '\"': Out << "\\\""; break;
452 case '\'': Out << "\\\'"; break;
455 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
456 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
465 if (CPA->getNumOperands()) {
467 printConstant(cast<Constant>(CPA->getOperand(0)));
468 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
470 printConstant(cast<Constant>(CPA->getOperand(i)));
477 void CWriter::printConstantPacked(ConstantPacked *CP) {
479 if (CP->getNumOperands()) {
481 printConstant(cast<Constant>(CP->getOperand(0)));
482 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
484 printConstant(cast<Constant>(CP->getOperand(i)));
490 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
491 // textually as a double (rather than as a reference to a stack-allocated
492 // variable). We decide this by converting CFP to a string and back into a
493 // double, and then checking whether the conversion results in a bit-equal
494 // double to the original value of CFP. This depends on us and the target C
495 // compiler agreeing on the conversion process (which is pretty likely since we
496 // only deal in IEEE FP).
498 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
501 sprintf(Buffer, "%a", CFP->getValue());
503 if (!strncmp(Buffer, "0x", 2) ||
504 !strncmp(Buffer, "-0x", 3) ||
505 !strncmp(Buffer, "+0x", 3))
506 return atof(Buffer) == CFP->getValue();
509 std::string StrVal = ftostr(CFP->getValue());
511 while (StrVal[0] == ' ')
512 StrVal.erase(StrVal.begin());
514 // Check to make sure that the stringized number is not some string like "Inf"
515 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
516 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
517 ((StrVal[0] == '-' || StrVal[0] == '+') &&
518 (StrVal[1] >= '0' && StrVal[1] <= '9')))
519 // Reparse stringized version!
520 return atof(StrVal.c_str()) == CFP->getValue();
525 // printConstant - The LLVM Constant to C Constant converter.
526 void CWriter::printConstant(Constant *CPV) {
527 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
528 switch (CE->getOpcode()) {
529 case Instruction::Cast:
531 printType(Out, CPV->getType());
533 printConstant(CE->getOperand(0));
537 case Instruction::GetElementPtr:
539 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
543 case Instruction::Select:
545 printConstant(CE->getOperand(0));
547 printConstant(CE->getOperand(1));
549 printConstant(CE->getOperand(2));
552 case Instruction::Add:
553 case Instruction::Sub:
554 case Instruction::Mul:
555 case Instruction::Div:
556 case Instruction::Rem:
557 case Instruction::And:
558 case Instruction::Or:
559 case Instruction::Xor:
560 case Instruction::SetEQ:
561 case Instruction::SetNE:
562 case Instruction::SetLT:
563 case Instruction::SetLE:
564 case Instruction::SetGT:
565 case Instruction::SetGE:
566 case Instruction::Shl:
567 case Instruction::Shr:
569 printConstant(CE->getOperand(0));
570 switch (CE->getOpcode()) {
571 case Instruction::Add: Out << " + "; break;
572 case Instruction::Sub: Out << " - "; break;
573 case Instruction::Mul: Out << " * "; break;
574 case Instruction::Div: Out << " / "; break;
575 case Instruction::Rem: Out << " % "; break;
576 case Instruction::And: Out << " & "; break;
577 case Instruction::Or: Out << " | "; break;
578 case Instruction::Xor: Out << " ^ "; break;
579 case Instruction::SetEQ: Out << " == "; break;
580 case Instruction::SetNE: Out << " != "; break;
581 case Instruction::SetLT: Out << " < "; break;
582 case Instruction::SetLE: Out << " <= "; break;
583 case Instruction::SetGT: Out << " > "; break;
584 case Instruction::SetGE: Out << " >= "; break;
585 case Instruction::Shl: Out << " << "; break;
586 case Instruction::Shr: Out << " >> "; break;
587 default: assert(0 && "Illegal opcode here!");
589 printConstant(CE->getOperand(1));
594 std::cerr << "CWriter Error: Unhandled constant expression: "
598 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
600 printType(Out, CPV->getType());
601 Out << ")/*UNDEF*/0)";
605 switch (CPV->getType()->getTypeID()) {
607 Out << (CPV == ConstantBool::False ? '0' : '1'); break;
608 case Type::SByteTyID:
609 case Type::ShortTyID:
610 Out << cast<ConstantSInt>(CPV)->getValue(); break;
612 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
613 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
615 Out << cast<ConstantSInt>(CPV)->getValue();
619 if (cast<ConstantSInt>(CPV)->isMinValue())
620 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
622 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
624 case Type::UByteTyID:
625 case Type::UShortTyID:
626 Out << cast<ConstantUInt>(CPV)->getValue(); break;
628 Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
629 case Type::ULongTyID:
630 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
632 case Type::FloatTyID:
633 case Type::DoubleTyID: {
634 ConstantFP *FPC = cast<ConstantFP>(CPV);
635 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
636 if (I != FPConstantMap.end()) {
637 // Because of FP precision problems we must load from a stack allocated
638 // value that holds the value in hex.
639 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
640 << "*)&FPConstant" << I->second << ')';
642 if (IsNAN(FPC->getValue())) {
645 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
647 const unsigned long QuietNaN = 0x7ff8UL;
648 const unsigned long SignalNaN = 0x7ff4UL;
650 // We need to grab the first part of the FP #
653 uint64_t ll = DoubleToBits(FPC->getValue());
654 sprintf(Buffer, "0x%llx", (unsigned long long)ll);
656 std::string Num(&Buffer[0], &Buffer[6]);
657 unsigned long Val = strtoul(Num.c_str(), 0, 16);
659 if (FPC->getType() == Type::FloatTy)
660 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
661 << Buffer << "\") /*nan*/ ";
663 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
664 << Buffer << "\") /*nan*/ ";
665 } else if (IsInf(FPC->getValue())) {
667 if (FPC->getValue() < 0) Out << '-';
668 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
673 // Print out the constant as a floating point number.
675 sprintf(Buffer, "%a", FPC->getValue());
678 Num = ftostr(FPC->getValue());
686 case Type::ArrayTyID:
687 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
688 const ArrayType *AT = cast<ArrayType>(CPV->getType());
690 if (AT->getNumElements()) {
692 Constant *CZ = Constant::getNullValue(AT->getElementType());
694 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
701 printConstantArray(cast<ConstantArray>(CPV));
705 case Type::PackedTyID:
706 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
707 const PackedType *AT = cast<PackedType>(CPV->getType());
709 if (AT->getNumElements()) {
711 Constant *CZ = Constant::getNullValue(AT->getElementType());
713 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
720 printConstantPacked(cast<ConstantPacked>(CPV));
724 case Type::StructTyID:
725 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
726 const StructType *ST = cast<StructType>(CPV->getType());
728 if (ST->getNumElements()) {
730 printConstant(Constant::getNullValue(ST->getElementType(0)));
731 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
733 printConstant(Constant::getNullValue(ST->getElementType(i)));
739 if (CPV->getNumOperands()) {
741 printConstant(cast<Constant>(CPV->getOperand(0)));
742 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
744 printConstant(cast<Constant>(CPV->getOperand(i)));
751 case Type::PointerTyID:
752 if (isa<ConstantPointerNull>(CPV)) {
754 printType(Out, CPV->getType());
755 Out << ")/*NULL*/0)";
757 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
763 std::cerr << "Unknown constant type: " << *CPV << "\n";
768 void CWriter::writeOperandInternal(Value *Operand) {
769 if (Instruction *I = dyn_cast<Instruction>(Operand))
770 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
771 // Should we inline this instruction to build a tree?
778 Constant* CPV = dyn_cast<Constant>(Operand);
779 if (CPV && !isa<GlobalValue>(CPV)) {
782 Out << Mang->getValueName(Operand);
786 void CWriter::writeOperand(Value *Operand) {
787 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
788 Out << "(&"; // Global variables are references as their addresses by llvm
790 writeOperandInternal(Operand);
792 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
796 // generateCompilerSpecificCode - This is where we add conditional compilation
797 // directives to cater to specific compilers as need be.
799 static void generateCompilerSpecificCode(std::ostream& Out) {
800 // Alloca is hard to get, and we don't want to include stdlib.h here.
801 Out << "/* get a declaration for alloca */\n"
802 << "#if defined(__CYGWIN__)\n"
803 << "extern void *_alloca(unsigned long);\n"
804 << "#define alloca(x) _alloca(x)\n"
805 << "#elif defined(__APPLE__)\n"
806 << "extern void *__builtin_alloca(unsigned long);\n"
807 << "#define alloca(x) __builtin_alloca(x)\n"
808 << "#elif defined(__sun__)\n"
809 << "#if defined(__sparcv9)\n"
810 << "extern void *__builtin_alloca(unsigned long);\n"
812 << "extern void *__builtin_alloca(unsigned int);\n"
814 << "#define alloca(x) __builtin_alloca(x)\n"
815 << "#elif defined(__FreeBSD__)\n"
816 << "#define alloca(x) __builtin_alloca(x)\n"
817 << "#elif !defined(_MSC_VER)\n"
818 << "#include <alloca.h>\n"
821 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
822 // If we aren't being compiled with GCC, just drop these attributes.
823 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
824 << "#define __attribute__(X)\n"
828 // At some point, we should support "external weak" vs. "weak" linkages.
829 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
830 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
831 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
832 << "#elif defined(__GNUC__)\n"
833 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
835 << "#define __EXTERNAL_WEAK__\n"
839 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
840 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
841 << "#define __ATTRIBUTE_WEAK__\n"
842 << "#elif defined(__GNUC__)\n"
843 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
845 << "#define __ATTRIBUTE_WEAK__\n"
848 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
849 // From the GCC documentation:
851 // double __builtin_nan (const char *str)
853 // This is an implementation of the ISO C99 function nan.
855 // Since ISO C99 defines this function in terms of strtod, which we do
856 // not implement, a description of the parsing is in order. The string is
857 // parsed as by strtol; that is, the base is recognized by leading 0 or
858 // 0x prefixes. The number parsed is placed in the significand such that
859 // the least significant bit of the number is at the least significant
860 // bit of the significand. The number is truncated to fit the significand
861 // field provided. The significand is forced to be a quiet NaN.
863 // This function, if given a string literal, is evaluated early enough
864 // that it is considered a compile-time constant.
866 // float __builtin_nanf (const char *str)
868 // Similar to __builtin_nan, except the return type is float.
870 // double __builtin_inf (void)
872 // Similar to __builtin_huge_val, except a warning is generated if the
873 // target floating-point format does not support infinities. This
874 // function is suitable for implementing the ISO C99 macro INFINITY.
876 // float __builtin_inff (void)
878 // Similar to __builtin_inf, except the return type is float.
879 Out << "#ifdef __GNUC__\n"
880 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
881 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
882 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
883 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
884 << "#define LLVM_INF __builtin_inf() /* Double */\n"
885 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
886 << "#define LLVM_PREFETCH(addr,rw,locality) "
887 "__builtin_prefetch(addr,rw,locality)\n"
888 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
889 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
891 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
892 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
893 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
894 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
895 << "#define LLVM_INF ((double)0.0) /* Double */\n"
896 << "#define LLVM_INFF 0.0F /* Float */\n"
897 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
898 << "#define __ATTRIBUTE_CTOR__\n"
899 << "#define __ATTRIBUTE_DTOR__\n"
902 // Output target-specific code that should be inserted into main.
903 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
904 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
905 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
906 << "#if defined(i386) || defined(__i386__) || defined(__i386)\n"
907 << "#undef CODE_FOR_MAIN\n"
908 << "#define CODE_FOR_MAIN() \\\n"
909 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
910 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
911 << "#endif\n#endif\n";
915 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
916 /// the StaticTors set.
917 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
918 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
919 if (!InitList) return;
921 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
922 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
923 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
925 if (CS->getOperand(1)->isNullValue())
926 return; // Found a null terminator, exit printing.
927 Constant *FP = CS->getOperand(1);
928 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
929 if (CE->getOpcode() == Instruction::Cast)
930 FP = CE->getOperand(0);
931 if (Function *F = dyn_cast<Function>(FP))
932 StaticTors.insert(F);
936 enum SpecialGlobalClass {
938 GlobalCtors, GlobalDtors,
942 /// getGlobalVariableClass - If this is a global that is specially recognized
943 /// by LLVM, return a code that indicates how we should handle it.
944 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
945 // If this is a global ctors/dtors list, handle it now.
946 if (GV->hasAppendingLinkage() && GV->use_empty()) {
947 if (GV->getName() == "llvm.global_ctors")
949 else if (GV->getName() == "llvm.global_dtors")
953 // Otherwise, it it is other metadata, don't print it. This catches things
954 // like debug information.
955 if (GV->getSection() == "llvm.metadata")
962 bool CWriter::doInitialization(Module &M) {
968 // Ensure that all structure types have names...
969 Mang = new Mangler(M);
970 Mang->markCharUnacceptable('.');
972 // Keep track of which functions are static ctors/dtors so they can have
973 // an attribute added to their prototypes.
974 std::set<Function*> StaticCtors, StaticDtors;
975 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
977 switch (getGlobalVariableClass(I)) {
980 FindStaticTors(I, StaticCtors);
983 FindStaticTors(I, StaticDtors);
988 // get declaration for alloca
989 Out << "/* Provide Declarations */\n";
990 Out << "#include <stdarg.h>\n"; // Varargs support
991 Out << "#include <setjmp.h>\n"; // Unwind support
992 generateCompilerSpecificCode(Out);
994 // Provide a definition for `bool' if not compiling with a C++ compiler.
996 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
998 << "\n\n/* Support for floating point constants */\n"
999 << "typedef unsigned long long ConstantDoubleTy;\n"
1000 << "typedef unsigned int ConstantFloatTy;\n"
1002 << "\n\n/* Global Declarations */\n";
1004 // First output all the declarations for the program, because C requires
1005 // Functions & globals to be declared before they are used.
1008 // Loop over the symbol table, emitting all named constants...
1009 printModuleTypes(M.getSymbolTable());
1011 // Global variable declarations...
1012 if (!M.global_empty()) {
1013 Out << "\n/* External Global Variable Declarations */\n";
1014 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1016 if (I->hasExternalLinkage()) {
1018 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1024 // Function declarations
1025 Out << "\n/* Function Declarations */\n";
1026 Out << "double fmod(double, double);\n"; // Support for FP rem
1027 Out << "float fmodf(float, float);\n";
1029 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1030 // Don't print declarations for intrinsic functions.
1031 if (!I->getIntrinsicID() &&
1032 I->getName() != "setjmp" && I->getName() != "longjmp") {
1033 printFunctionSignature(I, true);
1034 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1035 Out << " __ATTRIBUTE_WEAK__";
1036 if (StaticCtors.count(I))
1037 Out << " __ATTRIBUTE_CTOR__";
1038 if (StaticDtors.count(I))
1039 Out << " __ATTRIBUTE_DTOR__";
1044 // Output the global variable declarations
1045 if (!M.global_empty()) {
1046 Out << "\n\n/* Global Variable Declarations */\n";
1047 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1049 if (!I->isExternal()) {
1050 // Ignore special globals, such as debug info.
1051 if (getGlobalVariableClass(I))
1054 if (I->hasInternalLinkage())
1058 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1060 if (I->hasLinkOnceLinkage())
1061 Out << " __attribute__((common))";
1062 else if (I->hasWeakLinkage())
1063 Out << " __ATTRIBUTE_WEAK__";
1068 // Output the global variable definitions and contents...
1069 if (!M.global_empty()) {
1070 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1071 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1073 if (!I->isExternal()) {
1074 // Ignore special globals, such as debug info.
1075 if (getGlobalVariableClass(I))
1078 if (I->hasInternalLinkage())
1080 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1081 if (I->hasLinkOnceLinkage())
1082 Out << " __attribute__((common))";
1083 else if (I->hasWeakLinkage())
1084 Out << " __ATTRIBUTE_WEAK__";
1086 // If the initializer is not null, emit the initializer. If it is null,
1087 // we try to avoid emitting large amounts of zeros. The problem with
1088 // this, however, occurs when the variable has weak linkage. In this
1089 // case, the assembler will complain about the variable being both weak
1090 // and common, so we disable this optimization.
1091 if (!I->getInitializer()->isNullValue()) {
1093 writeOperand(I->getInitializer());
1094 } else if (I->hasWeakLinkage()) {
1095 // We have to specify an initializer, but it doesn't have to be
1096 // complete. If the value is an aggregate, print out { 0 }, and let
1097 // the compiler figure out the rest of the zeros.
1099 if (isa<StructType>(I->getInitializer()->getType()) ||
1100 isa<ArrayType>(I->getInitializer()->getType()) ||
1101 isa<PackedType>(I->getInitializer()->getType())) {
1104 // Just print it out normally.
1105 writeOperand(I->getInitializer());
1113 Out << "\n\n/* Function Bodies */\n";
1118 /// Output all floating point constants that cannot be printed accurately...
1119 void CWriter::printFloatingPointConstants(Function &F) {
1120 // Scan the module for floating point constants. If any FP constant is used
1121 // in the function, we want to redirect it here so that we do not depend on
1122 // the precision of the printed form, unless the printed form preserves
1125 static unsigned FPCounter = 0;
1126 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1128 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1129 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1130 !FPConstantMap.count(FPC)) {
1131 double Val = FPC->getValue();
1133 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1135 if (FPC->getType() == Type::DoubleTy) {
1136 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1137 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1138 << "ULL; /* " << Val << " */\n";
1139 } else if (FPC->getType() == Type::FloatTy) {
1140 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1141 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1142 << "U; /* " << Val << " */\n";
1144 assert(0 && "Unknown float type!");
1151 /// printSymbolTable - Run through symbol table looking for type names. If a
1152 /// type name is found, emit its declaration...
1154 void CWriter::printModuleTypes(const SymbolTable &ST) {
1155 // We are only interested in the type plane of the symbol table.
1156 SymbolTable::type_const_iterator I = ST.type_begin();
1157 SymbolTable::type_const_iterator End = ST.type_end();
1159 // If there are no type names, exit early.
1160 if (I == End) return;
1162 // Print out forward declarations for structure types before anything else!
1163 Out << "/* Structure forward decls */\n";
1164 for (; I != End; ++I)
1165 if (const Type *STy = dyn_cast<StructType>(I->second)) {
1166 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1167 Out << Name << ";\n";
1168 TypeNames.insert(std::make_pair(STy, Name));
1173 // Now we can print out typedefs...
1174 Out << "/* Typedefs */\n";
1175 for (I = ST.type_begin(); I != End; ++I) {
1176 const Type *Ty = cast<Type>(I->second);
1177 std::string Name = "l_" + Mang->makeNameProper(I->first);
1179 printType(Out, Ty, Name);
1185 // Keep track of which structures have been printed so far...
1186 std::set<const StructType *> StructPrinted;
1188 // Loop over all structures then push them into the stack so they are
1189 // printed in the correct order.
1191 Out << "/* Structure contents */\n";
1192 for (I = ST.type_begin(); I != End; ++I)
1193 if (const StructType *STy = dyn_cast<StructType>(I->second))
1194 // Only print out used types!
1195 printContainedStructs(STy, StructPrinted);
1198 // Push the struct onto the stack and recursively push all structs
1199 // this one depends on.
1201 // TODO: Make this work properly with packed types
1203 void CWriter::printContainedStructs(const Type *Ty,
1204 std::set<const StructType*> &StructPrinted){
1205 // Don't walk through pointers.
1206 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1208 // Print all contained types first.
1209 for (Type::subtype_iterator I = Ty->subtype_begin(),
1210 E = Ty->subtype_end(); I != E; ++I)
1211 printContainedStructs(*I, StructPrinted);
1213 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1214 // Check to see if we have already printed this struct.
1215 if (StructPrinted.insert(STy).second) {
1216 // Print structure type out.
1217 std::string Name = TypeNames[STy];
1218 printType(Out, STy, Name, true);
1224 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1225 if (F->hasInternalLinkage()) Out << "static ";
1227 // Loop over the arguments, printing them...
1228 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1230 std::stringstream FunctionInnards;
1232 // Print out the name...
1233 FunctionInnards << Mang->getValueName(F) << '(';
1235 if (!F->isExternal()) {
1236 if (!F->arg_empty()) {
1237 std::string ArgName;
1238 if (F->arg_begin()->hasName() || !Prototype)
1239 ArgName = Mang->getValueName(F->arg_begin());
1240 printType(FunctionInnards, F->arg_begin()->getType(), ArgName);
1241 for (Function::const_arg_iterator I = ++F->arg_begin(), E = F->arg_end();
1243 FunctionInnards << ", ";
1244 if (I->hasName() || !Prototype)
1245 ArgName = Mang->getValueName(I);
1248 printType(FunctionInnards, I->getType(), ArgName);
1252 // Loop over the arguments, printing them...
1253 for (FunctionType::param_iterator I = FT->param_begin(),
1254 E = FT->param_end(); I != E; ++I) {
1255 if (I != FT->param_begin()) FunctionInnards << ", ";
1256 printType(FunctionInnards, *I);
1260 // Finish printing arguments... if this is a vararg function, print the ...,
1261 // unless there are no known types, in which case, we just emit ().
1263 if (FT->isVarArg() && FT->getNumParams()) {
1264 if (FT->getNumParams()) FunctionInnards << ", ";
1265 FunctionInnards << "..."; // Output varargs portion of signature!
1266 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
1267 FunctionInnards << "void"; // ret() -> ret(void) in C.
1269 FunctionInnards << ')';
1270 // Print out the return type and the entire signature for that matter
1271 printType(Out, F->getReturnType(), FunctionInnards.str());
1274 void CWriter::printFunction(Function &F) {
1275 printFunctionSignature(&F, false);
1278 // print local variable information for the function
1279 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1280 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1282 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1283 Out << "; /* Address-exposed local */\n";
1284 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1286 printType(Out, I->getType(), Mang->getValueName(&*I));
1289 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1291 printType(Out, I->getType(),
1292 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1299 if (F.hasExternalLinkage() && F.getName() == "main")
1300 Out << " CODE_FOR_MAIN();\n";
1302 // print the basic blocks
1303 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1304 if (Loop *L = LI->getLoopFor(BB)) {
1305 if (L->getHeader() == BB && L->getParentLoop() == 0)
1308 printBasicBlock(BB);
1315 void CWriter::printLoop(Loop *L) {
1316 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1317 << "' to make GCC happy */\n";
1318 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1319 BasicBlock *BB = L->getBlocks()[i];
1320 Loop *BBLoop = LI->getLoopFor(BB);
1322 printBasicBlock(BB);
1323 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1326 Out << " } while (1); /* end of syntactic loop '"
1327 << L->getHeader()->getName() << "' */\n";
1330 void CWriter::printBasicBlock(BasicBlock *BB) {
1332 // Don't print the label for the basic block if there are no uses, or if
1333 // the only terminator use is the predecessor basic block's terminator.
1334 // We have to scan the use list because PHI nodes use basic blocks too but
1335 // do not require a label to be generated.
1337 bool NeedsLabel = false;
1338 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1339 if (isGotoCodeNecessary(*PI, BB)) {
1344 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1346 // Output all of the instructions in the basic block...
1347 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1349 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1350 if (II->getType() != Type::VoidTy)
1359 // Don't emit prefix or suffix for the terminator...
1360 visit(*BB->getTerminator());
1364 // Specific Instruction type classes... note that all of the casts are
1365 // necessary because we use the instruction classes as opaque types...
1367 void CWriter::visitReturnInst(ReturnInst &I) {
1368 // Don't output a void return if this is the last basic block in the function
1369 if (I.getNumOperands() == 0 &&
1370 &*--I.getParent()->getParent()->end() == I.getParent() &&
1371 !I.getParent()->size() == 1) {
1376 if (I.getNumOperands()) {
1378 writeOperand(I.getOperand(0));
1383 void CWriter::visitSwitchInst(SwitchInst &SI) {
1386 writeOperand(SI.getOperand(0));
1387 Out << ") {\n default:\n";
1388 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1389 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1391 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1393 writeOperand(SI.getOperand(i));
1395 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1396 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1397 printBranchToBlock(SI.getParent(), Succ, 2);
1398 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1404 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1405 Out << " /*UNREACHABLE*/;\n";
1408 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1409 /// FIXME: This should be reenabled, but loop reordering safe!!
1412 if (next(Function::iterator(From)) != Function::iterator(To))
1413 return true; // Not the direct successor, we need a goto.
1415 //isa<SwitchInst>(From->getTerminator())
1417 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1422 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1423 BasicBlock *Successor,
1425 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1426 PHINode *PN = cast<PHINode>(I);
1427 // Now we have to do the printing.
1428 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1429 if (!isa<UndefValue>(IV)) {
1430 Out << std::string(Indent, ' ');
1431 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1433 Out << "; /* for PHI node */\n";
1438 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1440 if (isGotoCodeNecessary(CurBB, Succ)) {
1441 Out << std::string(Indent, ' ') << " goto ";
1447 // Branch instruction printing - Avoid printing out a branch to a basic block
1448 // that immediately succeeds the current one.
1450 void CWriter::visitBranchInst(BranchInst &I) {
1452 if (I.isConditional()) {
1453 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1455 writeOperand(I.getCondition());
1458 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1459 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1461 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1462 Out << " } else {\n";
1463 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1464 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1467 // First goto not necessary, assume second one is...
1469 writeOperand(I.getCondition());
1472 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1473 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1478 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1479 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1484 // PHI nodes get copied into temporary values at the end of predecessor basic
1485 // blocks. We now need to copy these temporary values into the REAL value for
1487 void CWriter::visitPHINode(PHINode &I) {
1489 Out << "__PHI_TEMPORARY";
1493 void CWriter::visitBinaryOperator(Instruction &I) {
1494 // binary instructions, shift instructions, setCond instructions.
1495 assert(!isa<PointerType>(I.getType()));
1497 // We must cast the results of binary operations which might be promoted.
1498 bool needsCast = false;
1499 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1500 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1501 || (I.getType() == Type::FloatTy)) {
1504 printType(Out, I.getType());
1508 // If this is a negation operation, print it out as such. For FP, we don't
1509 // want to print "-0.0 - X".
1510 if (BinaryOperator::isNeg(&I)) {
1512 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1514 } else if (I.getOpcode() == Instruction::Rem &&
1515 I.getType()->isFloatingPoint()) {
1516 // Output a call to fmod/fmodf instead of emitting a%b
1517 if (I.getType() == Type::FloatTy)
1521 writeOperand(I.getOperand(0));
1523 writeOperand(I.getOperand(1));
1526 writeOperand(I.getOperand(0));
1528 switch (I.getOpcode()) {
1529 case Instruction::Add: Out << " + "; break;
1530 case Instruction::Sub: Out << " - "; break;
1531 case Instruction::Mul: Out << '*'; break;
1532 case Instruction::Div: Out << '/'; break;
1533 case Instruction::Rem: Out << '%'; break;
1534 case Instruction::And: Out << " & "; break;
1535 case Instruction::Or: Out << " | "; break;
1536 case Instruction::Xor: Out << " ^ "; break;
1537 case Instruction::SetEQ: Out << " == "; break;
1538 case Instruction::SetNE: Out << " != "; break;
1539 case Instruction::SetLE: Out << " <= "; break;
1540 case Instruction::SetGE: Out << " >= "; break;
1541 case Instruction::SetLT: Out << " < "; break;
1542 case Instruction::SetGT: Out << " > "; break;
1543 case Instruction::Shl : Out << " << "; break;
1544 case Instruction::Shr : Out << " >> "; break;
1545 default: std::cerr << "Invalid operator type!" << I; abort();
1548 writeOperand(I.getOperand(1));
1556 void CWriter::visitCastInst(CastInst &I) {
1557 if (I.getType() == Type::BoolTy) {
1559 writeOperand(I.getOperand(0));
1564 printType(Out, I.getType());
1566 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1567 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1568 // Avoid "cast to pointer from integer of different size" warnings
1572 writeOperand(I.getOperand(0));
1575 void CWriter::visitSelectInst(SelectInst &I) {
1577 writeOperand(I.getCondition());
1579 writeOperand(I.getTrueValue());
1581 writeOperand(I.getFalseValue());
1586 void CWriter::lowerIntrinsics(Function &F) {
1587 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1588 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1589 if (CallInst *CI = dyn_cast<CallInst>(I++))
1590 if (Function *F = CI->getCalledFunction())
1591 switch (F->getIntrinsicID()) {
1592 case Intrinsic::not_intrinsic:
1593 case Intrinsic::vastart:
1594 case Intrinsic::vacopy:
1595 case Intrinsic::vaend:
1596 case Intrinsic::returnaddress:
1597 case Intrinsic::frameaddress:
1598 case Intrinsic::setjmp:
1599 case Intrinsic::longjmp:
1600 case Intrinsic::prefetch:
1601 // We directly implement these intrinsics
1604 // All other intrinsic calls we must lower.
1605 Instruction *Before = 0;
1606 if (CI != &BB->front())
1607 Before = prior(BasicBlock::iterator(CI));
1609 IL.LowerIntrinsicCall(CI);
1610 if (Before) { // Move iterator to instruction after call
1620 void CWriter::visitCallInst(CallInst &I) {
1621 // Handle intrinsic function calls first...
1622 if (Function *F = I.getCalledFunction())
1623 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1625 default: assert(0 && "Unknown LLVM intrinsic!");
1626 case Intrinsic::vastart:
1629 Out << "va_start(*(va_list*)";
1630 writeOperand(I.getOperand(1));
1632 // Output the last argument to the enclosing function...
1633 if (I.getParent()->getParent()->arg_empty()) {
1634 std::cerr << "The C backend does not currently support zero "
1635 << "argument varargs functions, such as '"
1636 << I.getParent()->getParent()->getName() << "'!\n";
1639 writeOperand(--I.getParent()->getParent()->arg_end());
1642 case Intrinsic::vaend:
1643 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
1644 Out << "0; va_end(*(va_list*)";
1645 writeOperand(I.getOperand(1));
1648 Out << "va_end(*(va_list*)0)";
1651 case Intrinsic::vacopy:
1653 Out << "va_copy(*(va_list*)";
1654 writeOperand(I.getOperand(1));
1655 Out << ", *(va_list*)";
1656 writeOperand(I.getOperand(2));
1659 case Intrinsic::returnaddress:
1660 Out << "__builtin_return_address(";
1661 writeOperand(I.getOperand(1));
1664 case Intrinsic::frameaddress:
1665 Out << "__builtin_frame_address(";
1666 writeOperand(I.getOperand(1));
1669 case Intrinsic::setjmp:
1670 Out << "setjmp(*(jmp_buf*)";
1671 writeOperand(I.getOperand(1));
1674 case Intrinsic::longjmp:
1675 Out << "longjmp(*(jmp_buf*)";
1676 writeOperand(I.getOperand(1));
1678 writeOperand(I.getOperand(2));
1681 case Intrinsic::prefetch:
1682 Out << "LLVM_PREFETCH((const void *)";
1683 writeOperand(I.getOperand(1));
1685 writeOperand(I.getOperand(2));
1687 writeOperand(I.getOperand(3));
1693 Value *Callee = I.getCalledValue();
1695 // GCC is really a PITA. It does not permit codegening casts of functions to
1696 // function pointers if they are in a call (it generates a trap instruction
1697 // instead!). We work around this by inserting a cast to void* in between the
1698 // function and the function pointer cast. Unfortunately, we can't just form
1699 // the constant expression here, because the folder will immediately nuke it.
1701 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1702 // that void* and function pointers have the same size. :( To deal with this
1703 // in the common case, we handle casts where the number of arguments passed
1706 bool WroteCallee = false;
1707 if (I.isTailCall()) Out << " /*tail*/ ";
1708 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1709 if (CE->getOpcode() == Instruction::Cast)
1710 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1711 const FunctionType *RFTy = RF->getFunctionType();
1712 if (RFTy->getNumParams() == I.getNumOperands()-1) {
1713 // If the call site expects a value, and the actual callee doesn't
1714 // provide one, return 0.
1715 if (I.getType() != Type::VoidTy &&
1716 RFTy->getReturnType() == Type::VoidTy)
1717 Out << "0 /*actual callee doesn't return value*/; ";
1720 // Ok, just cast the pointer type.
1722 printType(Out, CE->getType());
1730 const PointerType *PTy = cast<PointerType>(Callee->getType());
1731 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1732 const Type *RetTy = FTy->getReturnType();
1734 if (!WroteCallee) writeOperand(Callee);
1737 unsigned NumDeclaredParams = FTy->getNumParams();
1739 if (I.getNumOperands() != 1) {
1740 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1741 if (NumDeclaredParams && (*AI)->getType() != FTy->getParamType(0)) {
1743 printType(Out, FTy->getParamType(0));
1750 for (ArgNo = 1, ++AI; AI != AE; ++AI, ++ArgNo) {
1752 if (ArgNo < NumDeclaredParams &&
1753 (*AI)->getType() != FTy->getParamType(ArgNo)) {
1755 printType(Out, FTy->getParamType(ArgNo));
1764 void CWriter::visitMallocInst(MallocInst &I) {
1765 assert(0 && "lowerallocations pass didn't work!");
1768 void CWriter::visitAllocaInst(AllocaInst &I) {
1770 printType(Out, I.getType());
1771 Out << ") alloca(sizeof(";
1772 printType(Out, I.getType()->getElementType());
1774 if (I.isArrayAllocation()) {
1776 writeOperand(I.getOperand(0));
1781 void CWriter::visitFreeInst(FreeInst &I) {
1782 assert(0 && "lowerallocations pass didn't work!");
1785 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1786 gep_type_iterator E) {
1787 bool HasImplicitAddress = false;
1788 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1789 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1790 HasImplicitAddress = true;
1791 } else if (isDirectAlloca(Ptr)) {
1792 HasImplicitAddress = true;
1796 if (!HasImplicitAddress)
1797 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1799 writeOperandInternal(Ptr);
1803 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1804 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1807 writeOperandInternal(Ptr);
1809 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1811 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1814 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1815 "Can only have implicit address with direct accessing");
1817 if (HasImplicitAddress) {
1819 } else if (CI && CI->isNullValue()) {
1820 gep_type_iterator TmpI = I; ++TmpI;
1822 // Print out the -> operator if possible...
1823 if (TmpI != E && isa<StructType>(*TmpI)) {
1824 Out << (HasImplicitAddress ? "." : "->");
1825 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1831 if (isa<StructType>(*I)) {
1832 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1835 writeOperand(I.getOperand());
1840 void CWriter::visitLoadInst(LoadInst &I) {
1842 if (I.isVolatile()) {
1844 printType(Out, I.getType(), "volatile*");
1848 writeOperand(I.getOperand(0));
1854 void CWriter::visitStoreInst(StoreInst &I) {
1856 if (I.isVolatile()) {
1858 printType(Out, I.getOperand(0)->getType(), " volatile*");
1861 writeOperand(I.getPointerOperand());
1862 if (I.isVolatile()) Out << ')';
1864 writeOperand(I.getOperand(0));
1867 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1869 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1873 void CWriter::visitVAArgInst(VAArgInst &I) {
1874 Out << "va_arg(*(va_list*)";
1875 writeOperand(I.getOperand(0));
1877 printType(Out, I.getType());
1881 //===----------------------------------------------------------------------===//
1882 // External Interface declaration
1883 //===----------------------------------------------------------------------===//
1885 bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
1886 CodeGenFileType FileType, bool Fast) {
1887 if (FileType != TargetMachine::AssemblyFile) return true;
1889 PM.add(createLowerGCPass());
1890 PM.add(createLowerAllocationsPass(true));
1891 PM.add(createLowerInvokePass());
1892 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
1893 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
1894 PM.add(new CWriter(o, getIntrinsicLowering()));