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/ADT/StringExtras.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Config/config.h"
44 // Register the target.
45 RegisterTarget<CTargetMachine> X("c", " C backend");
47 /// NameAllUsedStructs - This pass inserts names for any unnamed structure
48 /// types that are used by the program.
50 class CBackendNameAllUsedStructs : public ModulePass {
51 void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.addRequired<FindUsedTypes>();
55 virtual const char *getPassName() const {
56 return "C backend type canonicalizer";
59 virtual bool runOnModule(Module &M);
62 /// CWriter - This class is the main chunk of code that converts an LLVM
63 /// module to a C translation unit.
64 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
66 IntrinsicLowering &IL;
69 const Module *TheModule;
70 std::map<const Type *, std::string> TypeNames;
72 std::map<const ConstantFP *, unsigned> FPConstantMap;
74 CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
76 virtual const char *getPassName() const { return "C backend"; }
78 void getAnalysisUsage(AnalysisUsage &AU) const {
79 AU.addRequired<LoopInfo>();
83 virtual bool doInitialization(Module &M);
85 bool runOnFunction(Function &F) {
86 LI = &getAnalysis<LoopInfo>();
88 // Output all floating point constants that cannot be printed accurately.
89 printFloatingPointConstants(F);
93 FPConstantMap.clear();
97 virtual bool doFinalization(Module &M) {
104 std::ostream &printType(std::ostream &Out, const Type *Ty,
105 const std::string &VariableName = "",
106 bool IgnoreName = false);
108 void writeOperand(Value *Operand);
109 void writeOperandInternal(Value *Operand);
112 void lowerIntrinsics(Function &F);
114 bool nameAllUsedStructureTypes(Module &M);
115 void printModule(Module *M);
116 void printModuleTypes(const SymbolTable &ST);
117 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
118 void printFloatingPointConstants(Function &F);
119 void printFunctionSignature(const Function *F, bool Prototype);
121 void printFunction(Function &);
122 void printBasicBlock(BasicBlock *BB);
123 void printLoop(Loop *L);
125 void printConstant(Constant *CPV);
126 void printConstantArray(ConstantArray *CPA);
128 // isInlinableInst - Attempt to inline instructions into their uses to build
129 // trees as much as possible. To do this, we have to consistently decide
130 // what is acceptable to inline, so that variable declarations don't get
131 // printed and an extra copy of the expr is not emitted.
133 static bool isInlinableInst(const Instruction &I) {
134 // Always inline setcc instructions, even if they are shared by multiple
135 // expressions. GCC generates horrible code if we don't.
136 if (isa<SetCondInst>(I)) return true;
138 // Must be an expression, must be used exactly once. If it is dead, we
139 // emit it inline where it would go.
140 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
141 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
142 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
143 // Don't inline a load across a store or other bad things!
146 // Only inline instruction it it's use is in the same BB as the inst.
147 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
150 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
151 // variables which are accessed with the & operator. This causes GCC to
152 // generate significantly better code than to emit alloca calls directly.
154 static const AllocaInst *isDirectAlloca(const Value *V) {
155 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
156 if (!AI) return false;
157 if (AI->isArrayAllocation())
158 return 0; // FIXME: we can also inline fixed size array allocas!
159 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
164 // Instruction visitation functions
165 friend class InstVisitor<CWriter>;
167 void visitReturnInst(ReturnInst &I);
168 void visitBranchInst(BranchInst &I);
169 void visitSwitchInst(SwitchInst &I);
170 void visitInvokeInst(InvokeInst &I) {
171 assert(0 && "Lowerinvoke pass didn't work!");
174 void visitUnwindInst(UnwindInst &I) {
175 assert(0 && "Lowerinvoke pass didn't work!");
177 void visitUnreachableInst(UnreachableInst &I);
179 void visitPHINode(PHINode &I);
180 void visitBinaryOperator(Instruction &I);
182 void visitCastInst (CastInst &I);
183 void visitSelectInst(SelectInst &I);
184 void visitCallInst (CallInst &I);
185 void visitCallSite (CallSite CS);
186 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
188 void visitMallocInst(MallocInst &I);
189 void visitAllocaInst(AllocaInst &I);
190 void visitFreeInst (FreeInst &I);
191 void visitLoadInst (LoadInst &I);
192 void visitStoreInst (StoreInst &I);
193 void visitGetElementPtrInst(GetElementPtrInst &I);
194 void visitVANextInst(VANextInst &I);
195 void visitVAArgInst (VAArgInst &I);
197 void visitInstruction(Instruction &I) {
198 std::cerr << "C Writer does not know about " << I;
202 void outputLValue(Instruction *I) {
203 Out << " " << Mang->getValueName(I) << " = ";
206 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
207 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
208 BasicBlock *Successor, unsigned Indent);
209 void printPHICopiesForSuccessors(BasicBlock *CurBlock,
211 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
213 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
214 gep_type_iterator E);
218 /// This method inserts names for any unnamed structure types that are used by
219 /// the program, and removes names from structure types that are not used by the
222 bool CBackendNameAllUsedStructs::runOnModule(Module &M) {
223 // Get a set of types that are used by the program...
224 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
226 // Loop over the module symbol table, removing types from UT that are
227 // already named, and removing names for structure types that are not used.
229 SymbolTable &MST = M.getSymbolTable();
230 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
232 SymbolTable::type_iterator I = TI++;
233 if (const StructType *STy = dyn_cast<StructType>(I->second)) {
234 // If this is not used, remove it from the symbol table.
235 std::set<const Type *>::iterator UTI = UT.find(STy);
243 // UT now contains types that are not named. Loop over it, naming
246 bool Changed = false;
247 unsigned RenameCounter = 0;
248 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
250 if (const StructType *ST = dyn_cast<StructType>(*I)) {
251 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
259 // Pass the Type* and the variable name and this prints out the variable
262 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
263 const std::string &NameSoFar,
265 if (Ty->isPrimitiveType())
266 switch (Ty->getTypeID()) {
267 case Type::VoidTyID: return Out << "void " << NameSoFar;
268 case Type::BoolTyID: return Out << "bool " << NameSoFar;
269 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
270 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
271 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
272 case Type::ShortTyID: return Out << "short " << NameSoFar;
273 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
274 case Type::IntTyID: return Out << "int " << NameSoFar;
275 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
276 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
277 case Type::FloatTyID: return Out << "float " << NameSoFar;
278 case Type::DoubleTyID: return Out << "double " << NameSoFar;
280 std::cerr << "Unknown primitive type: " << *Ty << "\n";
284 // Check to see if the type is named.
285 if (!IgnoreName || isa<OpaqueType>(Ty)) {
286 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
287 if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
290 switch (Ty->getTypeID()) {
291 case Type::FunctionTyID: {
292 const FunctionType *MTy = cast<FunctionType>(Ty);
293 std::stringstream FunctionInnards;
294 FunctionInnards << " (" << NameSoFar << ") (";
295 for (FunctionType::param_iterator I = MTy->param_begin(),
296 E = MTy->param_end(); I != E; ++I) {
297 if (I != MTy->param_begin())
298 FunctionInnards << ", ";
299 printType(FunctionInnards, *I, "");
301 if (MTy->isVarArg()) {
302 if (MTy->getNumParams())
303 FunctionInnards << ", ...";
304 } else if (!MTy->getNumParams()) {
305 FunctionInnards << "void";
307 FunctionInnards << ")";
308 std::string tstr = FunctionInnards.str();
309 printType(Out, MTy->getReturnType(), tstr);
312 case Type::StructTyID: {
313 const StructType *STy = cast<StructType>(Ty);
314 Out << NameSoFar + " {\n";
316 for (StructType::element_iterator I = STy->element_begin(),
317 E = STy->element_end(); I != E; ++I) {
319 printType(Out, *I, "field" + utostr(Idx++));
325 case Type::PointerTyID: {
326 const PointerType *PTy = cast<PointerType>(Ty);
327 std::string ptrName = "*" + NameSoFar;
329 if (isa<ArrayType>(PTy->getElementType()))
330 ptrName = "(" + ptrName + ")";
332 return printType(Out, PTy->getElementType(), ptrName);
335 case Type::ArrayTyID: {
336 const ArrayType *ATy = cast<ArrayType>(Ty);
337 unsigned NumElements = ATy->getNumElements();
338 return printType(Out, ATy->getElementType(),
339 NameSoFar + "[" + utostr(NumElements) + "]");
342 case Type::OpaqueTyID: {
343 static int Count = 0;
344 std::string TyName = "struct opaque_" + itostr(Count++);
345 assert(TypeNames.find(Ty) == TypeNames.end());
346 TypeNames[Ty] = TyName;
347 return Out << TyName << " " << NameSoFar;
350 assert(0 && "Unhandled case in getTypeProps!");
357 void CWriter::printConstantArray(ConstantArray *CPA) {
359 // As a special case, print the array as a string if it is an array of
360 // ubytes or an array of sbytes with positive values.
362 const Type *ETy = CPA->getType()->getElementType();
363 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
365 // Make sure the last character is a null char, as automatically added by C
366 if (isString && (CPA->getNumOperands() == 0 ||
367 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
372 // Keep track of whether the last number was a hexadecimal escape
373 bool LastWasHex = false;
375 // Do not include the last character, which we know is null
376 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
377 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
379 // Print it out literally if it is a printable character. The only thing
380 // to be careful about is when the last letter output was a hex escape
381 // code, in which case we have to be careful not to print out hex digits
382 // explicitly (the C compiler thinks it is a continuation of the previous
383 // character, sheesh...)
385 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
387 if (C == '"' || C == '\\')
394 case '\n': Out << "\\n"; break;
395 case '\t': Out << "\\t"; break;
396 case '\r': Out << "\\r"; break;
397 case '\v': Out << "\\v"; break;
398 case '\a': Out << "\\a"; break;
399 case '\"': Out << "\\\""; break;
400 case '\'': Out << "\\\'"; break;
403 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
404 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
413 if (CPA->getNumOperands()) {
415 printConstant(cast<Constant>(CPA->getOperand(0)));
416 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
418 printConstant(cast<Constant>(CPA->getOperand(i)));
425 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
426 // textually as a double (rather than as a reference to a stack-allocated
427 // variable). We decide this by converting CFP to a string and back into a
428 // double, and then checking whether the conversion results in a bit-equal
429 // double to the original value of CFP. This depends on us and the target C
430 // compiler agreeing on the conversion process (which is pretty likely since we
431 // only deal in IEEE FP).
433 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
436 sprintf(Buffer, "%a", CFP->getValue());
438 if (!strncmp(Buffer, "0x", 2) ||
439 !strncmp(Buffer, "-0x", 3) ||
440 !strncmp(Buffer, "+0x", 3))
441 return atof(Buffer) == CFP->getValue();
444 std::string StrVal = ftostr(CFP->getValue());
446 while (StrVal[0] == ' ')
447 StrVal.erase(StrVal.begin());
449 // Check to make sure that the stringized number is not some string like "Inf"
450 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
451 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
452 ((StrVal[0] == '-' || StrVal[0] == '+') &&
453 (StrVal[1] >= '0' && StrVal[1] <= '9')))
454 // Reparse stringized version!
455 return atof(StrVal.c_str()) == CFP->getValue();
460 // printConstant - The LLVM Constant to C Constant converter.
461 void CWriter::printConstant(Constant *CPV) {
462 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
463 switch (CE->getOpcode()) {
464 case Instruction::Cast:
466 printType(Out, CPV->getType());
468 printConstant(CE->getOperand(0));
472 case Instruction::GetElementPtr:
474 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
478 case Instruction::Select:
480 printConstant(CE->getOperand(0));
482 printConstant(CE->getOperand(1));
484 printConstant(CE->getOperand(2));
487 case Instruction::Add:
488 case Instruction::Sub:
489 case Instruction::Mul:
490 case Instruction::Div:
491 case Instruction::Rem:
492 case Instruction::SetEQ:
493 case Instruction::SetNE:
494 case Instruction::SetLT:
495 case Instruction::SetLE:
496 case Instruction::SetGT:
497 case Instruction::SetGE:
498 case Instruction::Shl:
499 case Instruction::Shr:
501 printConstant(CE->getOperand(0));
502 switch (CE->getOpcode()) {
503 case Instruction::Add: Out << " + "; break;
504 case Instruction::Sub: Out << " - "; break;
505 case Instruction::Mul: Out << " * "; break;
506 case Instruction::Div: Out << " / "; break;
507 case Instruction::Rem: Out << " % "; break;
508 case Instruction::SetEQ: Out << " == "; break;
509 case Instruction::SetNE: Out << " != "; break;
510 case Instruction::SetLT: Out << " < "; break;
511 case Instruction::SetLE: Out << " <= "; break;
512 case Instruction::SetGT: Out << " > "; break;
513 case Instruction::SetGE: Out << " >= "; break;
514 case Instruction::Shl: Out << " << "; break;
515 case Instruction::Shr: Out << " >> "; break;
516 default: assert(0 && "Illegal opcode here!");
518 printConstant(CE->getOperand(1));
523 std::cerr << "CWriter Error: Unhandled constant expression: "
527 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
529 printType(Out, CPV->getType());
530 Out << ")/*UNDEF*/0)";
534 switch (CPV->getType()->getTypeID()) {
536 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
537 case Type::SByteTyID:
538 case Type::ShortTyID:
539 Out << cast<ConstantSInt>(CPV)->getValue(); break;
541 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
542 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
544 Out << cast<ConstantSInt>(CPV)->getValue();
548 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
550 case Type::UByteTyID:
551 case Type::UShortTyID:
552 Out << cast<ConstantUInt>(CPV)->getValue(); break;
554 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
555 case Type::ULongTyID:
556 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
558 case Type::FloatTyID:
559 case Type::DoubleTyID: {
560 ConstantFP *FPC = cast<ConstantFP>(CPV);
561 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
562 if (I != FPConstantMap.end()) {
563 // Because of FP precision problems we must load from a stack allocated
564 // value that holds the value in hex.
565 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
566 << "*)&FPConstant" << I->second << ")";
568 if (IsNAN(FPC->getValue())) {
571 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
573 const unsigned long QuietNaN = 0x7ff8UL;
574 const unsigned long SignalNaN = 0x7ff4UL;
576 // We need to grab the first part of the FP #
583 DHex.d = FPC->getValue();
584 sprintf(Buffer, "0x%llx", (unsigned long long)DHex.ll);
586 std::string Num(&Buffer[0], &Buffer[6]);
587 unsigned long Val = strtoul(Num.c_str(), 0, 16);
589 if (FPC->getType() == Type::FloatTy)
590 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
591 << Buffer << "\") /*nan*/ ";
593 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
594 << Buffer << "\") /*nan*/ ";
595 } else if (IsInf(FPC->getValue())) {
597 if (FPC->getValue() < 0) Out << "-";
598 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
603 // Print out the constant as a floating point number.
605 sprintf(Buffer, "%a", FPC->getValue());
608 Num = ftostr(FPC->getValue());
616 case Type::ArrayTyID:
617 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
618 const ArrayType *AT = cast<ArrayType>(CPV->getType());
620 if (AT->getNumElements()) {
622 Constant *CZ = Constant::getNullValue(AT->getElementType());
624 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
631 printConstantArray(cast<ConstantArray>(CPV));
635 case Type::StructTyID:
636 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
637 const StructType *ST = cast<StructType>(CPV->getType());
639 if (ST->getNumElements()) {
641 printConstant(Constant::getNullValue(ST->getElementType(0)));
642 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
644 printConstant(Constant::getNullValue(ST->getElementType(i)));
650 if (CPV->getNumOperands()) {
652 printConstant(cast<Constant>(CPV->getOperand(0)));
653 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
655 printConstant(cast<Constant>(CPV->getOperand(i)));
662 case Type::PointerTyID:
663 if (isa<ConstantPointerNull>(CPV)) {
665 printType(Out, CPV->getType());
666 Out << ")/*NULL*/0)";
668 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
674 std::cerr << "Unknown constant type: " << *CPV << "\n";
679 void CWriter::writeOperandInternal(Value *Operand) {
680 if (Instruction *I = dyn_cast<Instruction>(Operand))
681 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
682 // Should we inline this instruction to build a tree?
689 Constant* CPV = dyn_cast<Constant>(Operand);
690 if (CPV && !isa<GlobalValue>(CPV)) {
693 Out << Mang->getValueName(Operand);
697 void CWriter::writeOperand(Value *Operand) {
698 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
699 Out << "(&"; // Global variables are references as their addresses by llvm
701 writeOperandInternal(Operand);
703 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
707 // generateCompilerSpecificCode - This is where we add conditional compilation
708 // directives to cater to specific compilers as need be.
710 static void generateCompilerSpecificCode(std::ostream& Out) {
711 // Alloca is hard to get, and we don't want to include stdlib.h here...
712 Out << "/* get a declaration for alloca */\n"
713 << "#if defined(sun) || defined(__CYGWIN__) || defined(__APPLE__)\n"
714 << "extern void *__builtin_alloca(unsigned long);\n"
715 << "#define alloca(x) __builtin_alloca(x)\n"
716 << "#elif defined(__FreeBSD__)\n"
717 << "#define alloca(x) __builtin_alloca(x)\n"
719 << "#include <alloca.h>\n"
722 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
723 // If we aren't being compiled with GCC, just drop these attributes.
724 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
725 << "#define __attribute__(X)\n"
729 // At some point, we should support "external weak" vs. "weak" linkages.
730 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
731 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
732 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
733 << "#elif defined(__GNUC__)\n"
734 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
736 << "#define __EXTERNAL_WEAK__\n"
740 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
741 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
742 << "#define __ATTRIBUTE_WEAK__\n"
743 << "#elif defined(__GNUC__)\n"
744 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
746 << "#define __ATTRIBUTE_WEAK__\n"
749 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
750 // From the GCC documentation:
752 // double __builtin_nan (const char *str)
754 // This is an implementation of the ISO C99 function nan.
756 // Since ISO C99 defines this function in terms of strtod, which we do
757 // not implement, a description of the parsing is in order. The string is
758 // parsed as by strtol; that is, the base is recognized by leading 0 or
759 // 0x prefixes. The number parsed is placed in the significand such that
760 // the least significant bit of the number is at the least significant
761 // bit of the significand. The number is truncated to fit the significand
762 // field provided. The significand is forced to be a quiet NaN.
764 // This function, if given a string literal, is evaluated early enough
765 // that it is considered a compile-time constant.
767 // float __builtin_nanf (const char *str)
769 // Similar to __builtin_nan, except the return type is float.
771 // double __builtin_inf (void)
773 // Similar to __builtin_huge_val, except a warning is generated if the
774 // target floating-point format does not support infinities. This
775 // function is suitable for implementing the ISO C99 macro INFINITY.
777 // float __builtin_inff (void)
779 // Similar to __builtin_inf, except the return type is float.
780 Out << "#ifdef __GNUC__\n"
781 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
782 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
783 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
784 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
785 << "#define LLVM_INF __builtin_inf() /* Double */\n"
786 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
788 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
789 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
790 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
791 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
792 << "#define LLVM_INF ((double)0.0) /* Double */\n"
793 << "#define LLVM_INFF 0.0F /* Float */\n"
797 bool CWriter::doInitialization(Module &M) {
803 // Ensure that all structure types have names...
804 Mang = new Mangler(M);
806 // get declaration for alloca
807 Out << "/* Provide Declarations */\n";
808 Out << "#include <stdarg.h>\n"; // Varargs support
809 Out << "#include <setjmp.h>\n"; // Unwind support
810 generateCompilerSpecificCode(Out);
812 // Provide a definition for `bool' if not compiling with a C++ compiler.
814 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
816 << "\n\n/* Support for floating point constants */\n"
817 << "typedef unsigned long long ConstantDoubleTy;\n"
818 << "typedef unsigned int ConstantFloatTy;\n"
820 << "\n\n/* Global Declarations */\n";
822 // First output all the declarations for the program, because C requires
823 // Functions & globals to be declared before they are used.
826 // Loop over the symbol table, emitting all named constants...
827 printModuleTypes(M.getSymbolTable());
829 // Global variable declarations...
831 Out << "\n/* External Global Variable Declarations */\n";
832 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
833 if (I->hasExternalLinkage()) {
835 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
841 // Function declarations
843 Out << "\n/* Function Declarations */\n";
844 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
845 // Don't print declarations for intrinsic functions.
846 if (!I->getIntrinsicID() &&
847 I->getName() != "setjmp" && I->getName() != "longjmp") {
848 printFunctionSignature(I, true);
849 if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
850 if (I->hasLinkOnceLinkage()) Out << " __ATTRIBUTE_WEAK__";
856 // Output the global variable declarations
858 Out << "\n\n/* Global Variable Declarations */\n";
859 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
860 if (!I->isExternal()) {
862 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
864 if (I->hasLinkOnceLinkage())
865 Out << " __attribute__((common))";
866 else if (I->hasWeakLinkage())
867 Out << " __ATTRIBUTE_WEAK__";
872 // Output the global variable definitions and contents...
874 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
875 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
876 if (!I->isExternal()) {
877 if (I->hasInternalLinkage())
879 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
880 if (I->hasLinkOnceLinkage())
881 Out << " __attribute__((common))";
882 else if (I->hasWeakLinkage())
883 Out << " __ATTRIBUTE_WEAK__";
885 // If the initializer is not null, emit the initializer. If it is null,
886 // we try to avoid emitting large amounts of zeros. The problem with
887 // this, however, occurs when the variable has weak linkage. In this
888 // case, the assembler will complain about the variable being both weak
889 // and common, so we disable this optimization.
890 if (!I->getInitializer()->isNullValue()) {
892 writeOperand(I->getInitializer());
893 } else if (I->hasWeakLinkage()) {
894 // We have to specify an initializer, but it doesn't have to be
895 // complete. If the value is an aggregate, print out { 0 }, and let
896 // the compiler figure out the rest of the zeros.
898 if (isa<StructType>(I->getInitializer()->getType()) ||
899 isa<ArrayType>(I->getInitializer()->getType())) {
902 // Just print it out normally.
903 writeOperand(I->getInitializer());
911 Out << "\n\n/* Function Bodies */\n";
916 /// Output all floating point constants that cannot be printed accurately...
917 void CWriter::printFloatingPointConstants(Function &F) {
928 // Scan the module for floating point constants. If any FP constant is used
929 // in the function, we want to redirect it here so that we do not depend on
930 // the precision of the printed form, unless the printed form preserves
933 static unsigned FPCounter = 0;
934 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
936 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
937 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
938 !FPConstantMap.count(FPC)) {
939 double Val = FPC->getValue();
941 FPConstantMap[FPC] = FPCounter; // Number the FP constants
943 if (FPC->getType() == Type::DoubleTy) {
945 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
946 << " = 0x" << std::hex << DBLUnion.U << std::dec
947 << "ULL; /* " << Val << " */\n";
948 } else if (FPC->getType() == Type::FloatTy) {
950 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
951 << " = 0x" << std::hex << FLTUnion.U << std::dec
952 << "U; /* " << Val << " */\n";
954 assert(0 && "Unknown float type!");
961 /// printSymbolTable - Run through symbol table looking for type names. If a
962 /// type name is found, emit it's declaration...
964 void CWriter::printModuleTypes(const SymbolTable &ST) {
965 // If there are no type names, exit early.
966 if ( ! ST.hasTypes() )
969 // We are only interested in the type plane of the symbol table...
970 SymbolTable::type_const_iterator I = ST.type_begin();
971 SymbolTable::type_const_iterator End = ST.type_end();
973 // Print out forward declarations for structure types before anything else!
974 Out << "/* Structure forward decls */\n";
975 for (; I != End; ++I)
976 if (const Type *STy = dyn_cast<StructType>(I->second)) {
977 std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
978 Out << Name << ";\n";
979 TypeNames.insert(std::make_pair(STy, Name));
984 // Now we can print out typedefs...
985 Out << "/* Typedefs */\n";
986 for (I = ST.type_begin(); I != End; ++I) {
987 const Type *Ty = cast<Type>(I->second);
988 std::string Name = "l_" + Mangler::makeNameProper(I->first);
990 printType(Out, Ty, Name);
996 // Keep track of which structures have been printed so far...
997 std::set<const StructType *> StructPrinted;
999 // Loop over all structures then push them into the stack so they are
1000 // printed in the correct order.
1002 Out << "/* Structure contents */\n";
1003 for (I = ST.type_begin(); I != End; ++I)
1004 if (const StructType *STy = dyn_cast<StructType>(I->second))
1005 // Only print out used types!
1006 printContainedStructs(STy, StructPrinted);
1009 // Push the struct onto the stack and recursively push all structs
1010 // this one depends on.
1011 void CWriter::printContainedStructs(const Type *Ty,
1012 std::set<const StructType*> &StructPrinted){
1013 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1014 //Check to see if we have already printed this struct
1015 if (StructPrinted.count(STy) == 0) {
1016 // Print all contained types first...
1017 for (StructType::element_iterator I = STy->element_begin(),
1018 E = STy->element_end(); I != E; ++I) {
1019 const Type *Ty1 = I->get();
1020 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
1021 printContainedStructs(*I, StructPrinted);
1024 //Print structure type out..
1025 StructPrinted.insert(STy);
1026 std::string Name = TypeNames[STy];
1027 printType(Out, STy, Name, true);
1031 // If it is an array, check contained types and continue
1032 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
1033 const Type *Ty1 = ATy->getElementType();
1034 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
1035 printContainedStructs(Ty1, StructPrinted);
1040 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1041 if (F->hasInternalLinkage()) Out << "static ";
1043 // Loop over the arguments, printing them...
1044 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1046 std::stringstream FunctionInnards;
1048 // Print out the name...
1049 FunctionInnards << Mang->getValueName(F) << "(";
1051 if (!F->isExternal()) {
1053 std::string ArgName;
1054 if (F->abegin()->hasName() || !Prototype)
1055 ArgName = Mang->getValueName(F->abegin());
1056 printType(FunctionInnards, F->afront().getType(), ArgName);
1057 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
1059 FunctionInnards << ", ";
1060 if (I->hasName() || !Prototype)
1061 ArgName = Mang->getValueName(I);
1064 printType(FunctionInnards, I->getType(), ArgName);
1068 // Loop over the arguments, printing them...
1069 for (FunctionType::param_iterator I = FT->param_begin(),
1070 E = FT->param_end(); I != E; ++I) {
1071 if (I != FT->param_begin()) FunctionInnards << ", ";
1072 printType(FunctionInnards, *I);
1076 // Finish printing arguments... if this is a vararg function, print the ...,
1077 // unless there are no known types, in which case, we just emit ().
1079 if (FT->isVarArg() && FT->getNumParams()) {
1080 if (FT->getNumParams()) FunctionInnards << ", ";
1081 FunctionInnards << "..."; // Output varargs portion of signature!
1082 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
1083 FunctionInnards << "void"; // ret() -> ret(void) in C.
1085 FunctionInnards << ")";
1086 // Print out the return type and the entire signature for that matter
1087 printType(Out, F->getReturnType(), FunctionInnards.str());
1090 void CWriter::printFunction(Function &F) {
1091 printFunctionSignature(&F, false);
1094 // print local variable information for the function
1095 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1096 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1098 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1099 Out << "; /* Address exposed local */\n";
1100 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1102 printType(Out, I->getType(), Mang->getValueName(&*I));
1105 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1107 printType(Out, I->getType(),
1108 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1115 // print the basic blocks
1116 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1117 if (Loop *L = LI->getLoopFor(BB)) {
1118 if (L->getHeader() == BB && L->getParentLoop() == 0)
1121 printBasicBlock(BB);
1128 void CWriter::printLoop(Loop *L) {
1129 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1130 << "' to make GCC happy */\n";
1131 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1132 BasicBlock *BB = L->getBlocks()[i];
1133 Loop *BBLoop = LI->getLoopFor(BB);
1135 printBasicBlock(BB);
1136 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1139 Out << " } while (1); /* end of syntactic loop '"
1140 << L->getHeader()->getName() << "' */\n";
1143 void CWriter::printBasicBlock(BasicBlock *BB) {
1145 // Don't print the label for the basic block if there are no uses, or if
1146 // the only terminator use is the predecessor basic block's terminator.
1147 // We have to scan the use list because PHI nodes use basic blocks too but
1148 // do not require a label to be generated.
1150 bool NeedsLabel = false;
1151 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1152 if (isGotoCodeNecessary(*PI, BB)) {
1157 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1159 // Output all of the instructions in the basic block...
1160 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1162 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1163 if (II->getType() != Type::VoidTy)
1172 // Don't emit prefix or suffix for the terminator...
1173 visit(*BB->getTerminator());
1177 // Specific Instruction type classes... note that all of the casts are
1178 // necessary because we use the instruction classes as opaque types...
1180 void CWriter::visitReturnInst(ReturnInst &I) {
1181 // Don't output a void return if this is the last basic block in the function
1182 if (I.getNumOperands() == 0 &&
1183 &*--I.getParent()->getParent()->end() == I.getParent() &&
1184 !I.getParent()->size() == 1) {
1189 if (I.getNumOperands()) {
1191 writeOperand(I.getOperand(0));
1196 void CWriter::visitSwitchInst(SwitchInst &SI) {
1199 writeOperand(SI.getOperand(0));
1200 Out << ") {\n default:\n";
1201 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1202 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1204 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1206 writeOperand(SI.getOperand(i));
1208 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1209 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1210 printBranchToBlock(SI.getParent(), Succ, 2);
1211 if (Succ == SI.getParent()->getNext())
1217 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1218 Out << " /*UNREACHABLE*/;\n";
1221 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1222 /// FIXME: This should be reenabled, but loop reordering safe!!
1225 if (From->getNext() != To) // Not the direct successor, we need a goto
1228 //isa<SwitchInst>(From->getTerminator())
1231 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1236 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1237 BasicBlock *Successor,
1239 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1240 PHINode *PN = cast<PHINode>(I);
1241 // Now we have to do the printing.
1242 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1243 if (!isa<UndefValue>(IV)) {
1244 Out << std::string(Indent, ' ');
1245 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1247 Out << "; /* for PHI node */\n";
1253 void CWriter::printPHICopiesForSuccessors(BasicBlock *CurBlock,
1255 for (succ_iterator SI = succ_begin(CurBlock), E = succ_end(CurBlock);
1257 for (BasicBlock::iterator I = SI->begin(); isa<PHINode>(I); ++I) {
1258 PHINode *PN = cast<PHINode>(I);
1259 // Now we have to do the printing.
1260 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1261 if (!isa<UndefValue>(IV)) {
1262 Out << std::string(Indent, ' ');
1263 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1265 Out << "; /* for PHI node */\n";
1271 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1273 if (isGotoCodeNecessary(CurBB, Succ)) {
1274 Out << std::string(Indent, ' ') << " goto ";
1280 // Branch instruction printing - Avoid printing out a branch to a basic block
1281 // that immediately succeeds the current one.
1283 void CWriter::visitBranchInst(BranchInst &I) {
1285 if (I.isConditional()) {
1286 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1288 writeOperand(I.getCondition());
1291 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1292 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1294 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1295 Out << " } else {\n";
1296 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1297 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1300 // First goto not necessary, assume second one is...
1302 writeOperand(I.getCondition());
1305 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1306 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1311 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1312 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1317 // PHI nodes get copied into temporary values at the end of predecessor basic
1318 // blocks. We now need to copy these temporary values into the REAL value for
1320 void CWriter::visitPHINode(PHINode &I) {
1322 Out << "__PHI_TEMPORARY";
1326 void CWriter::visitBinaryOperator(Instruction &I) {
1327 // binary instructions, shift instructions, setCond instructions.
1328 assert(!isa<PointerType>(I.getType()));
1330 // We must cast the results of binary operations which might be promoted.
1331 bool needsCast = false;
1332 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1333 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1334 || (I.getType() == Type::FloatTy)) {
1337 printType(Out, I.getType());
1341 writeOperand(I.getOperand(0));
1343 switch (I.getOpcode()) {
1344 case Instruction::Add: Out << " + "; break;
1345 case Instruction::Sub: Out << " - "; break;
1346 case Instruction::Mul: Out << "*"; break;
1347 case Instruction::Div: Out << "/"; break;
1348 case Instruction::Rem: Out << "%"; break;
1349 case Instruction::And: Out << " & "; break;
1350 case Instruction::Or: Out << " | "; break;
1351 case Instruction::Xor: Out << " ^ "; break;
1352 case Instruction::SetEQ: Out << " == "; break;
1353 case Instruction::SetNE: Out << " != "; break;
1354 case Instruction::SetLE: Out << " <= "; break;
1355 case Instruction::SetGE: Out << " >= "; break;
1356 case Instruction::SetLT: Out << " < "; break;
1357 case Instruction::SetGT: Out << " > "; break;
1358 case Instruction::Shl : Out << " << "; break;
1359 case Instruction::Shr : Out << " >> "; break;
1360 default: std::cerr << "Invalid operator type!" << I; abort();
1363 writeOperand(I.getOperand(1));
1370 void CWriter::visitCastInst(CastInst &I) {
1371 if (I.getType() == Type::BoolTy) {
1373 writeOperand(I.getOperand(0));
1378 printType(Out, I.getType());
1380 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1381 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1382 // Avoid "cast to pointer from integer of different size" warnings
1386 writeOperand(I.getOperand(0));
1389 void CWriter::visitSelectInst(SelectInst &I) {
1391 writeOperand(I.getCondition());
1393 writeOperand(I.getTrueValue());
1395 writeOperand(I.getFalseValue());
1400 void CWriter::lowerIntrinsics(Function &F) {
1401 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1402 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1403 if (CallInst *CI = dyn_cast<CallInst>(I++))
1404 if (Function *F = CI->getCalledFunction())
1405 switch (F->getIntrinsicID()) {
1406 case Intrinsic::not_intrinsic:
1407 case Intrinsic::vastart:
1408 case Intrinsic::vacopy:
1409 case Intrinsic::vaend:
1410 case Intrinsic::returnaddress:
1411 case Intrinsic::frameaddress:
1412 case Intrinsic::setjmp:
1413 case Intrinsic::longjmp:
1414 // We directly implement these intrinsics
1417 // All other intrinsic calls we must lower.
1418 Instruction *Before = CI->getPrev();
1419 IL.LowerIntrinsicCall(CI);
1420 if (Before) { // Move iterator to instruction after call
1430 void CWriter::visitCallInst(CallInst &I) {
1431 // Handle intrinsic function calls first...
1432 if (Function *F = I.getCalledFunction())
1433 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1435 default: assert(0 && "Unknown LLVM intrinsic!");
1436 case Intrinsic::vastart:
1439 Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1440 // Output the last argument to the enclosing function...
1441 if (I.getParent()->getParent()->aempty()) {
1442 std::cerr << "The C backend does not currently support zero "
1443 << "argument varargs functions, such as '"
1444 << I.getParent()->getParent()->getName() << "'!\n";
1447 writeOperand(&I.getParent()->getParent()->aback());
1450 case Intrinsic::vaend:
1451 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
1452 Out << "va_end(*(va_list*)&";
1453 writeOperand(I.getOperand(1));
1456 Out << "va_end(*(va_list*)0)";
1459 case Intrinsic::vacopy:
1461 Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1462 Out << "*(va_list*)&";
1463 writeOperand(I.getOperand(1));
1466 case Intrinsic::returnaddress:
1467 Out << "__builtin_return_address(";
1468 writeOperand(I.getOperand(1));
1471 case Intrinsic::frameaddress:
1472 Out << "__builtin_frame_address(";
1473 writeOperand(I.getOperand(1));
1476 case Intrinsic::setjmp:
1477 Out << "setjmp(*(jmp_buf*)";
1478 writeOperand(I.getOperand(1));
1481 case Intrinsic::longjmp:
1482 Out << "longjmp(*(jmp_buf*)";
1483 writeOperand(I.getOperand(1));
1485 writeOperand(I.getOperand(2));
1493 void CWriter::visitCallSite(CallSite CS) {
1494 const PointerType *PTy = cast<PointerType>(CS.getCalledValue()->getType());
1495 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1496 const Type *RetTy = FTy->getReturnType();
1498 writeOperand(CS.getCalledValue());
1501 if (CS.arg_begin() != CS.arg_end()) {
1502 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1505 for (++AI; AI != AE; ++AI) {
1513 void CWriter::visitMallocInst(MallocInst &I) {
1514 assert(0 && "lowerallocations pass didn't work!");
1517 void CWriter::visitAllocaInst(AllocaInst &I) {
1519 printType(Out, I.getType());
1520 Out << ") alloca(sizeof(";
1521 printType(Out, I.getType()->getElementType());
1523 if (I.isArrayAllocation()) {
1525 writeOperand(I.getOperand(0));
1530 void CWriter::visitFreeInst(FreeInst &I) {
1531 assert(0 && "lowerallocations pass didn't work!");
1534 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1535 gep_type_iterator E) {
1536 bool HasImplicitAddress = false;
1537 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1538 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1539 HasImplicitAddress = true;
1540 } else if (isDirectAlloca(Ptr)) {
1541 HasImplicitAddress = true;
1545 if (!HasImplicitAddress)
1546 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1548 writeOperandInternal(Ptr);
1552 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1553 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1556 writeOperandInternal(Ptr);
1558 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1560 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1563 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1564 "Can only have implicit address with direct accessing");
1566 if (HasImplicitAddress) {
1568 } else if (CI && CI->isNullValue()) {
1569 gep_type_iterator TmpI = I; ++TmpI;
1571 // Print out the -> operator if possible...
1572 if (TmpI != E && isa<StructType>(*TmpI)) {
1573 Out << (HasImplicitAddress ? "." : "->");
1574 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1580 if (isa<StructType>(*I)) {
1581 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1584 writeOperand(I.getOperand());
1589 void CWriter::visitLoadInst(LoadInst &I) {
1591 writeOperand(I.getOperand(0));
1594 void CWriter::visitStoreInst(StoreInst &I) {
1596 writeOperand(I.getPointerOperand());
1598 writeOperand(I.getOperand(0));
1601 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1603 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1607 void CWriter::visitVANextInst(VANextInst &I) {
1608 Out << Mang->getValueName(I.getOperand(0));
1609 Out << "; va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1610 printType(Out, I.getArgType());
1614 void CWriter::visitVAArgInst(VAArgInst &I) {
1616 Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1617 writeOperand(I.getOperand(0));
1618 Out << ");\n " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1619 printType(Out, I.getType());
1620 Out << ");\n va_end(Tmp); }";
1623 //===----------------------------------------------------------------------===//
1624 // External Interface declaration
1625 //===----------------------------------------------------------------------===//
1627 bool CTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &o) {
1628 PM.add(createLowerGCPass());
1629 PM.add(createLowerAllocationsPass());
1630 PM.add(createLowerInvokePass());
1631 PM.add(new CBackendNameAllUsedStructs());
1632 PM.add(new CWriter(o, getIntrinsicLowering()));