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/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Analysis/ConstantsScanner.h"
27 #include "llvm/Analysis/FindUsedTypes.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include "llvm/Support/InstVisitor.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Config/config.h"
49 // Register the target.
50 RegisterTarget<CTargetMachine> X("c", " C backend");
52 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53 /// any unnamed structure types that are used by the program, and merges
54 /// external functions with the same name.
56 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
57 void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<FindUsedTypes>();
61 virtual const char *getPassName() const {
62 return "C backend type canonicalizer";
65 virtual bool runOnModule(Module &M);
68 /// CWriter - This class is the main chunk of code that converts an LLVM
69 /// module to a C translation unit.
70 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
72 DefaultIntrinsicLowering IL;
75 const Module *TheModule;
76 std::map<const Type *, std::string> TypeNames;
78 std::map<const ConstantFP *, unsigned> FPConstantMap;
80 CWriter(std::ostream &o) : Out(o) {}
82 virtual const char *getPassName() const { return "C backend"; }
84 void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
89 virtual bool doInitialization(Module &M);
91 bool runOnFunction(Function &F) {
92 LI = &getAnalysis<LoopInfo>();
94 // Get rid of intrinsics we can't handle.
97 // Output all floating point constants that cannot be printed accurately.
98 printFloatingPointConstants(F);
100 // Ensure that no local symbols conflict with global symbols.
101 F.renameLocalSymbols();
104 FPConstantMap.clear();
108 virtual bool doFinalization(Module &M) {
115 std::ostream &printType(std::ostream &Out, const Type *Ty,
116 const std::string &VariableName = "",
117 bool IgnoreName = false);
119 void printStructReturnPointerFunctionType(std::ostream &Out,
120 const PointerType *Ty);
122 void writeOperand(Value *Operand);
123 void writeOperandInternal(Value *Operand);
126 void lowerIntrinsics(Function &F);
128 void printModule(Module *M);
129 void printModuleTypes(const SymbolTable &ST);
130 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
131 void printFloatingPointConstants(Function &F);
132 void printFunctionSignature(const Function *F, bool Prototype);
134 void printFunction(Function &);
135 void printBasicBlock(BasicBlock *BB);
136 void printLoop(Loop *L);
138 void printConstant(Constant *CPV);
139 void printConstantArray(ConstantArray *CPA);
140 void printConstantPacked(ConstantPacked *CP);
142 // isInlinableInst - Attempt to inline instructions into their uses to build
143 // trees as much as possible. To do this, we have to consistently decide
144 // what is acceptable to inline, so that variable declarations don't get
145 // printed and an extra copy of the expr is not emitted.
147 static bool isInlinableInst(const Instruction &I) {
148 // Always inline setcc instructions, even if they are shared by multiple
149 // expressions. GCC generates horrible code if we don't.
150 if (isa<SetCondInst>(I)) return true;
152 // Must be an expression, must be used exactly once. If it is dead, we
153 // emit it inline where it would go.
154 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
155 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
156 isa<LoadInst>(I) || isa<VAArgInst>(I))
157 // Don't inline a load across a store or other bad things!
160 // Only inline instruction it it's use is in the same BB as the inst.
161 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
164 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
165 // variables which are accessed with the & operator. This causes GCC to
166 // generate significantly better code than to emit alloca calls directly.
168 static const AllocaInst *isDirectAlloca(const Value *V) {
169 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
170 if (!AI) return false;
171 if (AI->isArrayAllocation())
172 return 0; // FIXME: we can also inline fixed size array allocas!
173 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
178 // Instruction visitation functions
179 friend class InstVisitor<CWriter>;
181 void visitReturnInst(ReturnInst &I);
182 void visitBranchInst(BranchInst &I);
183 void visitSwitchInst(SwitchInst &I);
184 void visitInvokeInst(InvokeInst &I) {
185 assert(0 && "Lowerinvoke pass didn't work!");
188 void visitUnwindInst(UnwindInst &I) {
189 assert(0 && "Lowerinvoke pass didn't work!");
191 void visitUnreachableInst(UnreachableInst &I);
193 void visitPHINode(PHINode &I);
194 void visitBinaryOperator(Instruction &I);
196 void visitCastInst (CastInst &I);
197 void visitSelectInst(SelectInst &I);
198 void visitCallInst (CallInst &I);
199 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
201 void visitMallocInst(MallocInst &I);
202 void visitAllocaInst(AllocaInst &I);
203 void visitFreeInst (FreeInst &I);
204 void visitLoadInst (LoadInst &I);
205 void visitStoreInst (StoreInst &I);
206 void visitGetElementPtrInst(GetElementPtrInst &I);
207 void visitVAArgInst (VAArgInst &I);
209 void visitInstruction(Instruction &I) {
210 std::cerr << "C Writer does not know about " << I;
214 void outputLValue(Instruction *I) {
215 Out << " " << Mang->getValueName(I) << " = ";
218 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
219 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
220 BasicBlock *Successor, unsigned Indent);
221 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
223 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
224 gep_type_iterator E);
228 /// This method inserts names for any unnamed structure types that are used by
229 /// the program, and removes names from structure types that are not used by the
232 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
233 // Get a set of types that are used by the program...
234 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
236 // Loop over the module symbol table, removing types from UT that are
237 // already named, and removing names for types that are not used.
239 SymbolTable &MST = M.getSymbolTable();
240 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
242 SymbolTable::type_iterator I = TI++;
244 // If this is not used, remove it from the symbol table.
245 std::set<const Type *>::iterator UTI = UT.find(I->second);
249 UT.erase(UTI); // Only keep one name for this type.
252 // UT now contains types that are not named. Loop over it, naming
255 bool Changed = false;
256 unsigned RenameCounter = 0;
257 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
259 if (const StructType *ST = dyn_cast<StructType>(*I)) {
260 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
266 // Loop over all external functions and globals. If we have two with
267 // identical names, merge them.
268 // FIXME: This code should disappear when we don't allow values with the same
269 // names when they have different types!
270 std::map<std::string, GlobalValue*> ExtSymbols;
271 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
273 if (GV->isExternal() && GV->hasName()) {
274 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
275 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
277 // Found a conflict, replace this global with the previous one.
278 GlobalValue *OldGV = X.first->second;
279 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
280 GV->eraseFromParent();
285 // Do the same for globals.
286 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
288 GlobalVariable *GV = I++;
289 if (GV->isExternal() && GV->hasName()) {
290 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
291 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
293 // Found a conflict, replace this global with the previous one.
294 GlobalValue *OldGV = X.first->second;
295 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
296 GV->eraseFromParent();
305 /// printStructReturnPointerFunctionType - This is like printType for a struct
306 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
307 /// print it as "Struct (*)(...)", for struct return functions.
308 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
309 const PointerType *TheTy) {
310 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
311 std::stringstream FunctionInnards;
312 FunctionInnards << " (*) (";
313 bool PrintedType = false;
315 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
316 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
317 for (++I; I != E; ++I) {
319 FunctionInnards << ", ";
320 printType(FunctionInnards, *I, "");
323 if (FTy->isVarArg()) {
325 FunctionInnards << ", ...";
326 } else if (!PrintedType) {
327 FunctionInnards << "void";
329 FunctionInnards << ')';
330 std::string tstr = FunctionInnards.str();
331 printType(Out, RetTy, tstr);
335 // Pass the Type* and the variable name and this prints out the variable
338 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
339 const std::string &NameSoFar,
341 if (Ty->isPrimitiveType())
342 switch (Ty->getTypeID()) {
343 case Type::VoidTyID: return Out << "void " << NameSoFar;
344 case Type::BoolTyID: return Out << "bool " << NameSoFar;
345 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
346 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
347 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
348 case Type::ShortTyID: return Out << "short " << NameSoFar;
349 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
350 case Type::IntTyID: return Out << "int " << NameSoFar;
351 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
352 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
353 case Type::FloatTyID: return Out << "float " << NameSoFar;
354 case Type::DoubleTyID: return Out << "double " << NameSoFar;
356 std::cerr << "Unknown primitive type: " << *Ty << "\n";
360 // Check to see if the type is named.
361 if (!IgnoreName || isa<OpaqueType>(Ty)) {
362 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
363 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
366 switch (Ty->getTypeID()) {
367 case Type::FunctionTyID: {
368 const FunctionType *FTy = cast<FunctionType>(Ty);
369 std::stringstream FunctionInnards;
370 FunctionInnards << " (" << NameSoFar << ") (";
371 for (FunctionType::param_iterator I = FTy->param_begin(),
372 E = FTy->param_end(); I != E; ++I) {
373 if (I != FTy->param_begin())
374 FunctionInnards << ", ";
375 printType(FunctionInnards, *I, "");
377 if (FTy->isVarArg()) {
378 if (FTy->getNumParams())
379 FunctionInnards << ", ...";
380 } else if (!FTy->getNumParams()) {
381 FunctionInnards << "void";
383 FunctionInnards << ')';
384 std::string tstr = FunctionInnards.str();
385 printType(Out, FTy->getReturnType(), tstr);
388 case Type::StructTyID: {
389 const StructType *STy = cast<StructType>(Ty);
390 Out << NameSoFar + " {\n";
392 for (StructType::element_iterator I = STy->element_begin(),
393 E = STy->element_end(); I != E; ++I) {
395 printType(Out, *I, "field" + utostr(Idx++));
401 case Type::PointerTyID: {
402 const PointerType *PTy = cast<PointerType>(Ty);
403 std::string ptrName = "*" + NameSoFar;
405 if (isa<ArrayType>(PTy->getElementType()) ||
406 isa<PackedType>(PTy->getElementType()))
407 ptrName = "(" + ptrName + ")";
409 return printType(Out, PTy->getElementType(), ptrName);
412 case Type::ArrayTyID: {
413 const ArrayType *ATy = cast<ArrayType>(Ty);
414 unsigned NumElements = ATy->getNumElements();
415 if (NumElements == 0) NumElements = 1;
416 return printType(Out, ATy->getElementType(),
417 NameSoFar + "[" + utostr(NumElements) + "]");
420 case Type::PackedTyID: {
421 const PackedType *PTy = cast<PackedType>(Ty);
422 unsigned NumElements = PTy->getNumElements();
423 if (NumElements == 0) NumElements = 1;
424 return printType(Out, PTy->getElementType(),
425 NameSoFar + "[" + utostr(NumElements) + "]");
428 case Type::OpaqueTyID: {
429 static int Count = 0;
430 std::string TyName = "struct opaque_" + itostr(Count++);
431 assert(TypeNames.find(Ty) == TypeNames.end());
432 TypeNames[Ty] = TyName;
433 return Out << TyName << ' ' << NameSoFar;
436 assert(0 && "Unhandled case in getTypeProps!");
443 void CWriter::printConstantArray(ConstantArray *CPA) {
445 // As a special case, print the array as a string if it is an array of
446 // ubytes or an array of sbytes with positive values.
448 const Type *ETy = CPA->getType()->getElementType();
449 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
451 // Make sure the last character is a null char, as automatically added by C
452 if (isString && (CPA->getNumOperands() == 0 ||
453 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
458 // Keep track of whether the last number was a hexadecimal escape
459 bool LastWasHex = false;
461 // Do not include the last character, which we know is null
462 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
463 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
465 // Print it out literally if it is a printable character. The only thing
466 // to be careful about is when the last letter output was a hex escape
467 // code, in which case we have to be careful not to print out hex digits
468 // explicitly (the C compiler thinks it is a continuation of the previous
469 // character, sheesh...)
471 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
473 if (C == '"' || C == '\\')
480 case '\n': Out << "\\n"; break;
481 case '\t': Out << "\\t"; break;
482 case '\r': Out << "\\r"; break;
483 case '\v': Out << "\\v"; break;
484 case '\a': Out << "\\a"; break;
485 case '\"': Out << "\\\""; break;
486 case '\'': Out << "\\\'"; break;
489 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
490 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
499 if (CPA->getNumOperands()) {
501 printConstant(cast<Constant>(CPA->getOperand(0)));
502 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
504 printConstant(cast<Constant>(CPA->getOperand(i)));
511 void CWriter::printConstantPacked(ConstantPacked *CP) {
513 if (CP->getNumOperands()) {
515 printConstant(cast<Constant>(CP->getOperand(0)));
516 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
518 printConstant(cast<Constant>(CP->getOperand(i)));
524 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
525 // textually as a double (rather than as a reference to a stack-allocated
526 // variable). We decide this by converting CFP to a string and back into a
527 // double, and then checking whether the conversion results in a bit-equal
528 // double to the original value of CFP. This depends on us and the target C
529 // compiler agreeing on the conversion process (which is pretty likely since we
530 // only deal in IEEE FP).
532 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
535 sprintf(Buffer, "%a", CFP->getValue());
537 if (!strncmp(Buffer, "0x", 2) ||
538 !strncmp(Buffer, "-0x", 3) ||
539 !strncmp(Buffer, "+0x", 3))
540 return atof(Buffer) == CFP->getValue();
543 std::string StrVal = ftostr(CFP->getValue());
545 while (StrVal[0] == ' ')
546 StrVal.erase(StrVal.begin());
548 // Check to make sure that the stringized number is not some string like "Inf"
549 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
550 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
551 ((StrVal[0] == '-' || StrVal[0] == '+') &&
552 (StrVal[1] >= '0' && StrVal[1] <= '9')))
553 // Reparse stringized version!
554 return atof(StrVal.c_str()) == CFP->getValue();
559 // printConstant - The LLVM Constant to C Constant converter.
560 void CWriter::printConstant(Constant *CPV) {
561 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
562 switch (CE->getOpcode()) {
563 case Instruction::Cast:
565 printType(Out, CPV->getType());
567 printConstant(CE->getOperand(0));
571 case Instruction::GetElementPtr:
573 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
577 case Instruction::Select:
579 printConstant(CE->getOperand(0));
581 printConstant(CE->getOperand(1));
583 printConstant(CE->getOperand(2));
586 case Instruction::Add:
587 case Instruction::Sub:
588 case Instruction::Mul:
589 case Instruction::Div:
590 case Instruction::Rem:
591 case Instruction::And:
592 case Instruction::Or:
593 case Instruction::Xor:
594 case Instruction::SetEQ:
595 case Instruction::SetNE:
596 case Instruction::SetLT:
597 case Instruction::SetLE:
598 case Instruction::SetGT:
599 case Instruction::SetGE:
600 case Instruction::Shl:
601 case Instruction::Shr:
603 printConstant(CE->getOperand(0));
604 switch (CE->getOpcode()) {
605 case Instruction::Add: Out << " + "; break;
606 case Instruction::Sub: Out << " - "; break;
607 case Instruction::Mul: Out << " * "; break;
608 case Instruction::Div: Out << " / "; break;
609 case Instruction::Rem: Out << " % "; break;
610 case Instruction::And: Out << " & "; break;
611 case Instruction::Or: Out << " | "; break;
612 case Instruction::Xor: Out << " ^ "; break;
613 case Instruction::SetEQ: Out << " == "; break;
614 case Instruction::SetNE: Out << " != "; break;
615 case Instruction::SetLT: Out << " < "; break;
616 case Instruction::SetLE: Out << " <= "; break;
617 case Instruction::SetGT: Out << " > "; break;
618 case Instruction::SetGE: Out << " >= "; break;
619 case Instruction::Shl: Out << " << "; break;
620 case Instruction::Shr: Out << " >> "; break;
621 default: assert(0 && "Illegal opcode here!");
623 printConstant(CE->getOperand(1));
628 std::cerr << "CWriter Error: Unhandled constant expression: "
632 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
634 printType(Out, CPV->getType());
635 Out << ")/*UNDEF*/0)";
639 switch (CPV->getType()->getTypeID()) {
641 Out << (CPV == ConstantBool::False ? '0' : '1'); break;
642 case Type::SByteTyID:
643 case Type::ShortTyID:
644 Out << cast<ConstantSInt>(CPV)->getValue(); break;
646 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
647 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
649 Out << cast<ConstantSInt>(CPV)->getValue();
653 if (cast<ConstantSInt>(CPV)->isMinValue())
654 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
656 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
658 case Type::UByteTyID:
659 case Type::UShortTyID:
660 Out << cast<ConstantUInt>(CPV)->getValue(); break;
662 Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
663 case Type::ULongTyID:
664 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
666 case Type::FloatTyID:
667 case Type::DoubleTyID: {
668 ConstantFP *FPC = cast<ConstantFP>(CPV);
669 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
670 if (I != FPConstantMap.end()) {
671 // Because of FP precision problems we must load from a stack allocated
672 // value that holds the value in hex.
673 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
674 << "*)&FPConstant" << I->second << ')';
676 if (IsNAN(FPC->getValue())) {
679 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
681 const unsigned long QuietNaN = 0x7ff8UL;
682 const unsigned long SignalNaN = 0x7ff4UL;
684 // We need to grab the first part of the FP #
687 uint64_t ll = DoubleToBits(FPC->getValue());
688 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
690 std::string Num(&Buffer[0], &Buffer[6]);
691 unsigned long Val = strtoul(Num.c_str(), 0, 16);
693 if (FPC->getType() == Type::FloatTy)
694 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
695 << Buffer << "\") /*nan*/ ";
697 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
698 << Buffer << "\") /*nan*/ ";
699 } else if (IsInf(FPC->getValue())) {
701 if (FPC->getValue() < 0) Out << '-';
702 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
707 // Print out the constant as a floating point number.
709 sprintf(Buffer, "%a", FPC->getValue());
712 Num = ftostr(FPC->getValue());
720 case Type::ArrayTyID:
721 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
722 const ArrayType *AT = cast<ArrayType>(CPV->getType());
724 if (AT->getNumElements()) {
726 Constant *CZ = Constant::getNullValue(AT->getElementType());
728 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
735 printConstantArray(cast<ConstantArray>(CPV));
739 case Type::PackedTyID:
740 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
741 const PackedType *AT = cast<PackedType>(CPV->getType());
743 if (AT->getNumElements()) {
745 Constant *CZ = Constant::getNullValue(AT->getElementType());
747 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
754 printConstantPacked(cast<ConstantPacked>(CPV));
758 case Type::StructTyID:
759 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
760 const StructType *ST = cast<StructType>(CPV->getType());
762 if (ST->getNumElements()) {
764 printConstant(Constant::getNullValue(ST->getElementType(0)));
765 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
767 printConstant(Constant::getNullValue(ST->getElementType(i)));
773 if (CPV->getNumOperands()) {
775 printConstant(cast<Constant>(CPV->getOperand(0)));
776 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
778 printConstant(cast<Constant>(CPV->getOperand(i)));
785 case Type::PointerTyID:
786 if (isa<ConstantPointerNull>(CPV)) {
788 printType(Out, CPV->getType());
789 Out << ")/*NULL*/0)";
791 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
797 std::cerr << "Unknown constant type: " << *CPV << "\n";
802 void CWriter::writeOperandInternal(Value *Operand) {
803 if (Instruction *I = dyn_cast<Instruction>(Operand))
804 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
805 // Should we inline this instruction to build a tree?
812 Constant* CPV = dyn_cast<Constant>(Operand);
813 if (CPV && !isa<GlobalValue>(CPV)) {
816 Out << Mang->getValueName(Operand);
820 void CWriter::writeOperand(Value *Operand) {
821 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
822 Out << "(&"; // Global variables are references as their addresses by llvm
824 writeOperandInternal(Operand);
826 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
830 // generateCompilerSpecificCode - This is where we add conditional compilation
831 // directives to cater to specific compilers as need be.
833 static void generateCompilerSpecificCode(std::ostream& Out) {
834 // Alloca is hard to get, and we don't want to include stdlib.h here.
835 Out << "/* get a declaration for alloca */\n"
836 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
837 << "extern void *_alloca(unsigned long);\n"
838 << "#define alloca(x) _alloca(x)\n"
839 << "#elif defined(__APPLE__)\n"
840 << "extern void *__builtin_alloca(unsigned long);\n"
841 << "#define alloca(x) __builtin_alloca(x)\n"
842 << "#elif defined(__sun__)\n"
843 << "#if defined(__sparcv9)\n"
844 << "extern void *__builtin_alloca(unsigned long);\n"
846 << "extern void *__builtin_alloca(unsigned int);\n"
848 << "#define alloca(x) __builtin_alloca(x)\n"
849 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
850 << "#define alloca(x) __builtin_alloca(x)\n"
851 << "#elif !defined(_MSC_VER)\n"
852 << "#include <alloca.h>\n"
855 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
856 // If we aren't being compiled with GCC, just drop these attributes.
857 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
858 << "#define __attribute__(X)\n"
862 // At some point, we should support "external weak" vs. "weak" linkages.
863 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
864 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
865 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
866 << "#elif defined(__GNUC__)\n"
867 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
869 << "#define __EXTERNAL_WEAK__\n"
873 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
874 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
875 << "#define __ATTRIBUTE_WEAK__\n"
876 << "#elif defined(__GNUC__)\n"
877 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
879 << "#define __ATTRIBUTE_WEAK__\n"
882 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
883 // From the GCC documentation:
885 // double __builtin_nan (const char *str)
887 // This is an implementation of the ISO C99 function nan.
889 // Since ISO C99 defines this function in terms of strtod, which we do
890 // not implement, a description of the parsing is in order. The string is
891 // parsed as by strtol; that is, the base is recognized by leading 0 or
892 // 0x prefixes. The number parsed is placed in the significand such that
893 // the least significant bit of the number is at the least significant
894 // bit of the significand. The number is truncated to fit the significand
895 // field provided. The significand is forced to be a quiet NaN.
897 // This function, if given a string literal, is evaluated early enough
898 // that it is considered a compile-time constant.
900 // float __builtin_nanf (const char *str)
902 // Similar to __builtin_nan, except the return type is float.
904 // double __builtin_inf (void)
906 // Similar to __builtin_huge_val, except a warning is generated if the
907 // target floating-point format does not support infinities. This
908 // function is suitable for implementing the ISO C99 macro INFINITY.
910 // float __builtin_inff (void)
912 // Similar to __builtin_inf, except the return type is float.
913 Out << "#ifdef __GNUC__\n"
914 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
915 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
916 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
917 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
918 << "#define LLVM_INF __builtin_inf() /* Double */\n"
919 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
920 << "#define LLVM_PREFETCH(addr,rw,locality) "
921 "__builtin_prefetch(addr,rw,locality)\n"
922 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
923 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
925 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
926 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
927 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
928 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
929 << "#define LLVM_INF ((double)0.0) /* Double */\n"
930 << "#define LLVM_INFF 0.0F /* Float */\n"
931 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
932 << "#define __ATTRIBUTE_CTOR__\n"
933 << "#define __ATTRIBUTE_DTOR__\n"
936 // Output target-specific code that should be inserted into main.
937 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
938 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
939 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
940 << "#if defined(i386) || defined(__i386__) || defined(__i386)\n"
941 << "#undef CODE_FOR_MAIN\n"
942 << "#define CODE_FOR_MAIN() \\\n"
943 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
944 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
945 << "#endif\n#endif\n";
949 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
950 /// the StaticTors set.
951 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
952 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
953 if (!InitList) return;
955 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
956 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
957 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
959 if (CS->getOperand(1)->isNullValue())
960 return; // Found a null terminator, exit printing.
961 Constant *FP = CS->getOperand(1);
962 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
963 if (CE->getOpcode() == Instruction::Cast)
964 FP = CE->getOperand(0);
965 if (Function *F = dyn_cast<Function>(FP))
966 StaticTors.insert(F);
970 enum SpecialGlobalClass {
972 GlobalCtors, GlobalDtors,
976 /// getGlobalVariableClass - If this is a global that is specially recognized
977 /// by LLVM, return a code that indicates how we should handle it.
978 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
979 // If this is a global ctors/dtors list, handle it now.
980 if (GV->hasAppendingLinkage() && GV->use_empty()) {
981 if (GV->getName() == "llvm.global_ctors")
983 else if (GV->getName() == "llvm.global_dtors")
987 // Otherwise, it it is other metadata, don't print it. This catches things
988 // like debug information.
989 if (GV->getSection() == "llvm.metadata")
996 bool CWriter::doInitialization(Module &M) {
1000 IL.AddPrototypes(M);
1002 // Ensure that all structure types have names...
1003 Mang = new Mangler(M);
1004 Mang->markCharUnacceptable('.');
1006 // Keep track of which functions are static ctors/dtors so they can have
1007 // an attribute added to their prototypes.
1008 std::set<Function*> StaticCtors, StaticDtors;
1009 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1011 switch (getGlobalVariableClass(I)) {
1014 FindStaticTors(I, StaticCtors);
1017 FindStaticTors(I, StaticDtors);
1022 // get declaration for alloca
1023 Out << "/* Provide Declarations */\n";
1024 Out << "#include <stdarg.h>\n"; // Varargs support
1025 Out << "#include <setjmp.h>\n"; // Unwind support
1026 generateCompilerSpecificCode(Out);
1028 // Provide a definition for `bool' if not compiling with a C++ compiler.
1030 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1032 << "\n\n/* Support for floating point constants */\n"
1033 << "typedef unsigned long long ConstantDoubleTy;\n"
1034 << "typedef unsigned int ConstantFloatTy;\n"
1036 << "\n\n/* Global Declarations */\n";
1038 // First output all the declarations for the program, because C requires
1039 // Functions & globals to be declared before they are used.
1042 // Loop over the symbol table, emitting all named constants...
1043 printModuleTypes(M.getSymbolTable());
1045 // Global variable declarations...
1046 if (!M.global_empty()) {
1047 Out << "\n/* External Global Variable Declarations */\n";
1048 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1050 if (I->hasExternalLinkage()) {
1052 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1058 // Function declarations
1059 Out << "\n/* Function Declarations */\n";
1060 Out << "double fmod(double, double);\n"; // Support for FP rem
1061 Out << "float fmodf(float, float);\n";
1063 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1064 // Don't print declarations for intrinsic functions.
1065 if (!I->getIntrinsicID() &&
1066 I->getName() != "setjmp" && I->getName() != "longjmp") {
1067 printFunctionSignature(I, true);
1068 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1069 Out << " __ATTRIBUTE_WEAK__";
1070 if (StaticCtors.count(I))
1071 Out << " __ATTRIBUTE_CTOR__";
1072 if (StaticDtors.count(I))
1073 Out << " __ATTRIBUTE_DTOR__";
1078 // Output the global variable declarations
1079 if (!M.global_empty()) {
1080 Out << "\n\n/* Global Variable Declarations */\n";
1081 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1083 if (!I->isExternal()) {
1084 // Ignore special globals, such as debug info.
1085 if (getGlobalVariableClass(I))
1088 if (I->hasInternalLinkage())
1092 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1094 if (I->hasLinkOnceLinkage())
1095 Out << " __attribute__((common))";
1096 else if (I->hasWeakLinkage())
1097 Out << " __ATTRIBUTE_WEAK__";
1102 // Output the global variable definitions and contents...
1103 if (!M.global_empty()) {
1104 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1105 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1107 if (!I->isExternal()) {
1108 // Ignore special globals, such as debug info.
1109 if (getGlobalVariableClass(I))
1112 if (I->hasInternalLinkage())
1114 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1115 if (I->hasLinkOnceLinkage())
1116 Out << " __attribute__((common))";
1117 else if (I->hasWeakLinkage())
1118 Out << " __ATTRIBUTE_WEAK__";
1120 // If the initializer is not null, emit the initializer. If it is null,
1121 // we try to avoid emitting large amounts of zeros. The problem with
1122 // this, however, occurs when the variable has weak linkage. In this
1123 // case, the assembler will complain about the variable being both weak
1124 // and common, so we disable this optimization.
1125 if (!I->getInitializer()->isNullValue()) {
1127 writeOperand(I->getInitializer());
1128 } else if (I->hasWeakLinkage()) {
1129 // We have to specify an initializer, but it doesn't have to be
1130 // complete. If the value is an aggregate, print out { 0 }, and let
1131 // the compiler figure out the rest of the zeros.
1133 if (isa<StructType>(I->getInitializer()->getType()) ||
1134 isa<ArrayType>(I->getInitializer()->getType()) ||
1135 isa<PackedType>(I->getInitializer()->getType())) {
1138 // Just print it out normally.
1139 writeOperand(I->getInitializer());
1147 Out << "\n\n/* Function Bodies */\n";
1152 /// Output all floating point constants that cannot be printed accurately...
1153 void CWriter::printFloatingPointConstants(Function &F) {
1154 // Scan the module for floating point constants. If any FP constant is used
1155 // in the function, we want to redirect it here so that we do not depend on
1156 // the precision of the printed form, unless the printed form preserves
1159 static unsigned FPCounter = 0;
1160 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1162 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1163 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1164 !FPConstantMap.count(FPC)) {
1165 double Val = FPC->getValue();
1167 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1169 if (FPC->getType() == Type::DoubleTy) {
1170 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1171 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1172 << "ULL; /* " << Val << " */\n";
1173 } else if (FPC->getType() == Type::FloatTy) {
1174 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1175 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1176 << "U; /* " << Val << " */\n";
1178 assert(0 && "Unknown float type!");
1185 /// printSymbolTable - Run through symbol table looking for type names. If a
1186 /// type name is found, emit its declaration...
1188 void CWriter::printModuleTypes(const SymbolTable &ST) {
1189 // We are only interested in the type plane of the symbol table.
1190 SymbolTable::type_const_iterator I = ST.type_begin();
1191 SymbolTable::type_const_iterator End = ST.type_end();
1193 // If there are no type names, exit early.
1194 if (I == End) return;
1196 // Print out forward declarations for structure types before anything else!
1197 Out << "/* Structure forward decls */\n";
1198 for (; I != End; ++I)
1199 if (const Type *STy = dyn_cast<StructType>(I->second)) {
1200 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1201 Out << Name << ";\n";
1202 TypeNames.insert(std::make_pair(STy, Name));
1207 // Now we can print out typedefs...
1208 Out << "/* Typedefs */\n";
1209 for (I = ST.type_begin(); I != End; ++I) {
1210 const Type *Ty = cast<Type>(I->second);
1211 std::string Name = "l_" + Mang->makeNameProper(I->first);
1213 printType(Out, Ty, Name);
1219 // Keep track of which structures have been printed so far...
1220 std::set<const StructType *> StructPrinted;
1222 // Loop over all structures then push them into the stack so they are
1223 // printed in the correct order.
1225 Out << "/* Structure contents */\n";
1226 for (I = ST.type_begin(); I != End; ++I)
1227 if (const StructType *STy = dyn_cast<StructType>(I->second))
1228 // Only print out used types!
1229 printContainedStructs(STy, StructPrinted);
1232 // Push the struct onto the stack and recursively push all structs
1233 // this one depends on.
1235 // TODO: Make this work properly with packed types
1237 void CWriter::printContainedStructs(const Type *Ty,
1238 std::set<const StructType*> &StructPrinted){
1239 // Don't walk through pointers.
1240 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1242 // Print all contained types first.
1243 for (Type::subtype_iterator I = Ty->subtype_begin(),
1244 E = Ty->subtype_end(); I != E; ++I)
1245 printContainedStructs(*I, StructPrinted);
1247 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1248 // Check to see if we have already printed this struct.
1249 if (StructPrinted.insert(STy).second) {
1250 // Print structure type out.
1251 std::string Name = TypeNames[STy];
1252 printType(Out, STy, Name, true);
1258 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1259 /// isCStructReturn - Should this function actually return a struct by-value?
1260 bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1262 if (F->hasInternalLinkage()) Out << "static ";
1264 // Loop over the arguments, printing them...
1265 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1267 std::stringstream FunctionInnards;
1269 // Print out the name...
1270 FunctionInnards << Mang->getValueName(F) << '(';
1272 bool PrintedArg = false;
1273 if (!F->isExternal()) {
1274 if (!F->arg_empty()) {
1275 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1277 // If this is a struct-return function, don't print the hidden
1278 // struct-return argument.
1279 if (isCStructReturn) {
1280 assert(I != E && "Invalid struct return function!");
1284 std::string ArgName;
1285 for (; I != E; ++I) {
1286 if (PrintedArg) FunctionInnards << ", ";
1287 if (I->hasName() || !Prototype)
1288 ArgName = Mang->getValueName(I);
1291 printType(FunctionInnards, I->getType(), ArgName);
1296 // Loop over the arguments, printing them.
1297 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1299 // If this is a struct-return function, don't print the hidden
1300 // struct-return argument.
1301 if (isCStructReturn) {
1302 assert(I != E && "Invalid struct return function!");
1306 for (; I != E; ++I) {
1307 if (PrintedArg) FunctionInnards << ", ";
1308 printType(FunctionInnards, *I);
1313 // Finish printing arguments... if this is a vararg function, print the ...,
1314 // unless there are no known types, in which case, we just emit ().
1316 if (FT->isVarArg() && PrintedArg) {
1317 if (PrintedArg) FunctionInnards << ", ";
1318 FunctionInnards << "..."; // Output varargs portion of signature!
1319 } else if (!FT->isVarArg() && !PrintedArg) {
1320 FunctionInnards << "void"; // ret() -> ret(void) in C.
1322 FunctionInnards << ')';
1324 // Get the return tpe for the function.
1326 if (!isCStructReturn)
1327 RetTy = F->getReturnType();
1329 // If this is a struct-return function, print the struct-return type.
1330 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1333 // Print out the return type and the signature built above.
1334 printType(Out, RetTy, FunctionInnards.str());
1337 void CWriter::printFunction(Function &F) {
1338 printFunctionSignature(&F, false);
1341 // If this is a struct return function, handle the result with magic.
1342 if (F.getCallingConv() == CallingConv::CSRet) {
1343 const Type *StructTy =
1344 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1346 printType(Out, StructTy, "StructReturn");
1347 Out << "; /* Struct return temporary */\n";
1350 printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1351 Out << " = &StructReturn;\n";
1354 bool PrintedVar = false;
1356 // print local variable information for the function
1357 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1358 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1360 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1361 Out << "; /* Address-exposed local */\n";
1363 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1365 printType(Out, I->getType(), Mang->getValueName(&*I));
1368 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1370 printType(Out, I->getType(),
1371 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1380 if (F.hasExternalLinkage() && F.getName() == "main")
1381 Out << " CODE_FOR_MAIN();\n";
1383 // print the basic blocks
1384 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1385 if (Loop *L = LI->getLoopFor(BB)) {
1386 if (L->getHeader() == BB && L->getParentLoop() == 0)
1389 printBasicBlock(BB);
1396 void CWriter::printLoop(Loop *L) {
1397 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1398 << "' to make GCC happy */\n";
1399 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1400 BasicBlock *BB = L->getBlocks()[i];
1401 Loop *BBLoop = LI->getLoopFor(BB);
1403 printBasicBlock(BB);
1404 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1407 Out << " } while (1); /* end of syntactic loop '"
1408 << L->getHeader()->getName() << "' */\n";
1411 void CWriter::printBasicBlock(BasicBlock *BB) {
1413 // Don't print the label for the basic block if there are no uses, or if
1414 // the only terminator use is the predecessor basic block's terminator.
1415 // We have to scan the use list because PHI nodes use basic blocks too but
1416 // do not require a label to be generated.
1418 bool NeedsLabel = false;
1419 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1420 if (isGotoCodeNecessary(*PI, BB)) {
1425 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1427 // Output all of the instructions in the basic block...
1428 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1430 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1431 if (II->getType() != Type::VoidTy)
1440 // Don't emit prefix or suffix for the terminator...
1441 visit(*BB->getTerminator());
1445 // Specific Instruction type classes... note that all of the casts are
1446 // necessary because we use the instruction classes as opaque types...
1448 void CWriter::visitReturnInst(ReturnInst &I) {
1449 // If this is a struct return function, return the temporary struct.
1450 if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1451 Out << " return StructReturn;\n";
1455 // Don't output a void return if this is the last basic block in the function
1456 if (I.getNumOperands() == 0 &&
1457 &*--I.getParent()->getParent()->end() == I.getParent() &&
1458 !I.getParent()->size() == 1) {
1463 if (I.getNumOperands()) {
1465 writeOperand(I.getOperand(0));
1470 void CWriter::visitSwitchInst(SwitchInst &SI) {
1473 writeOperand(SI.getOperand(0));
1474 Out << ") {\n default:\n";
1475 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1476 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1478 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1480 writeOperand(SI.getOperand(i));
1482 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1483 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1484 printBranchToBlock(SI.getParent(), Succ, 2);
1485 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1491 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1492 Out << " /*UNREACHABLE*/;\n";
1495 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1496 /// FIXME: This should be reenabled, but loop reordering safe!!
1499 if (next(Function::iterator(From)) != Function::iterator(To))
1500 return true; // Not the direct successor, we need a goto.
1502 //isa<SwitchInst>(From->getTerminator())
1504 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1509 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1510 BasicBlock *Successor,
1512 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1513 PHINode *PN = cast<PHINode>(I);
1514 // Now we have to do the printing.
1515 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1516 if (!isa<UndefValue>(IV)) {
1517 Out << std::string(Indent, ' ');
1518 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1520 Out << "; /* for PHI node */\n";
1525 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1527 if (isGotoCodeNecessary(CurBB, Succ)) {
1528 Out << std::string(Indent, ' ') << " goto ";
1534 // Branch instruction printing - Avoid printing out a branch to a basic block
1535 // that immediately succeeds the current one.
1537 void CWriter::visitBranchInst(BranchInst &I) {
1539 if (I.isConditional()) {
1540 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1542 writeOperand(I.getCondition());
1545 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1546 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1548 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1549 Out << " } else {\n";
1550 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1551 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1554 // First goto not necessary, assume second one is...
1556 writeOperand(I.getCondition());
1559 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1560 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1565 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1566 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1571 // PHI nodes get copied into temporary values at the end of predecessor basic
1572 // blocks. We now need to copy these temporary values into the REAL value for
1574 void CWriter::visitPHINode(PHINode &I) {
1576 Out << "__PHI_TEMPORARY";
1580 void CWriter::visitBinaryOperator(Instruction &I) {
1581 // binary instructions, shift instructions, setCond instructions.
1582 assert(!isa<PointerType>(I.getType()));
1584 // We must cast the results of binary operations which might be promoted.
1585 bool needsCast = false;
1586 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1587 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1588 || (I.getType() == Type::FloatTy)) {
1591 printType(Out, I.getType());
1595 // If this is a negation operation, print it out as such. For FP, we don't
1596 // want to print "-0.0 - X".
1597 if (BinaryOperator::isNeg(&I)) {
1599 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1601 } else if (I.getOpcode() == Instruction::Rem &&
1602 I.getType()->isFloatingPoint()) {
1603 // Output a call to fmod/fmodf instead of emitting a%b
1604 if (I.getType() == Type::FloatTy)
1608 writeOperand(I.getOperand(0));
1610 writeOperand(I.getOperand(1));
1613 writeOperand(I.getOperand(0));
1615 switch (I.getOpcode()) {
1616 case Instruction::Add: Out << " + "; break;
1617 case Instruction::Sub: Out << " - "; break;
1618 case Instruction::Mul: Out << '*'; break;
1619 case Instruction::Div: Out << '/'; break;
1620 case Instruction::Rem: Out << '%'; break;
1621 case Instruction::And: Out << " & "; break;
1622 case Instruction::Or: Out << " | "; break;
1623 case Instruction::Xor: Out << " ^ "; break;
1624 case Instruction::SetEQ: Out << " == "; break;
1625 case Instruction::SetNE: Out << " != "; break;
1626 case Instruction::SetLE: Out << " <= "; break;
1627 case Instruction::SetGE: Out << " >= "; break;
1628 case Instruction::SetLT: Out << " < "; break;
1629 case Instruction::SetGT: Out << " > "; break;
1630 case Instruction::Shl : Out << " << "; break;
1631 case Instruction::Shr : Out << " >> "; break;
1632 default: std::cerr << "Invalid operator type!" << I; abort();
1635 writeOperand(I.getOperand(1));
1643 void CWriter::visitCastInst(CastInst &I) {
1644 if (I.getType() == Type::BoolTy) {
1646 writeOperand(I.getOperand(0));
1651 printType(Out, I.getType());
1653 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1654 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1655 // Avoid "cast to pointer from integer of different size" warnings
1659 writeOperand(I.getOperand(0));
1662 void CWriter::visitSelectInst(SelectInst &I) {
1664 writeOperand(I.getCondition());
1666 writeOperand(I.getTrueValue());
1668 writeOperand(I.getFalseValue());
1673 void CWriter::lowerIntrinsics(Function &F) {
1674 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1675 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1676 if (CallInst *CI = dyn_cast<CallInst>(I++))
1677 if (Function *F = CI->getCalledFunction())
1678 switch (F->getIntrinsicID()) {
1679 case Intrinsic::not_intrinsic:
1680 case Intrinsic::vastart:
1681 case Intrinsic::vacopy:
1682 case Intrinsic::vaend:
1683 case Intrinsic::returnaddress:
1684 case Intrinsic::frameaddress:
1685 case Intrinsic::setjmp:
1686 case Intrinsic::longjmp:
1687 case Intrinsic::prefetch:
1688 case Intrinsic::dbg_stoppoint:
1689 // We directly implement these intrinsics
1692 // If this is an intrinsic that directly corresponds to a GCC
1693 // builtin, we handle it.
1694 const char *BuiltinName = "";
1695 #define GET_GCC_BUILTIN_NAME
1696 #include "llvm/Intrinsics.gen"
1697 #undef GET_GCC_BUILTIN_NAME
1698 // If we handle it, don't lower it.
1699 if (BuiltinName[0]) break;
1701 // All other intrinsic calls we must lower.
1702 Instruction *Before = 0;
1703 if (CI != &BB->front())
1704 Before = prior(BasicBlock::iterator(CI));
1706 IL.LowerIntrinsicCall(CI);
1707 if (Before) { // Move iterator to instruction after call
1718 void CWriter::visitCallInst(CallInst &I) {
1719 bool WroteCallee = false;
1721 // Handle intrinsic function calls first...
1722 if (Function *F = I.getCalledFunction())
1723 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1726 // If this is an intrinsic that directly corresponds to a GCC
1727 // builtin, we emit it here.
1728 const char *BuiltinName = "";
1729 #define GET_GCC_BUILTIN_NAME
1730 #include "llvm/Intrinsics.gen"
1731 #undef GET_GCC_BUILTIN_NAME
1732 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1738 case Intrinsic::vastart:
1741 Out << "va_start(*(va_list*)";
1742 writeOperand(I.getOperand(1));
1744 // Output the last argument to the enclosing function...
1745 if (I.getParent()->getParent()->arg_empty()) {
1746 std::cerr << "The C backend does not currently support zero "
1747 << "argument varargs functions, such as '"
1748 << I.getParent()->getParent()->getName() << "'!\n";
1751 writeOperand(--I.getParent()->getParent()->arg_end());
1754 case Intrinsic::vaend:
1755 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
1756 Out << "0; va_end(*(va_list*)";
1757 writeOperand(I.getOperand(1));
1760 Out << "va_end(*(va_list*)0)";
1763 case Intrinsic::vacopy:
1765 Out << "va_copy(*(va_list*)";
1766 writeOperand(I.getOperand(1));
1767 Out << ", *(va_list*)";
1768 writeOperand(I.getOperand(2));
1771 case Intrinsic::returnaddress:
1772 Out << "__builtin_return_address(";
1773 writeOperand(I.getOperand(1));
1776 case Intrinsic::frameaddress:
1777 Out << "__builtin_frame_address(";
1778 writeOperand(I.getOperand(1));
1781 case Intrinsic::setjmp:
1782 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1783 Out << "_"; // Use _setjmp on systems that support it!
1785 Out << "setjmp(*(jmp_buf*)";
1786 writeOperand(I.getOperand(1));
1789 case Intrinsic::longjmp:
1790 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1791 Out << "_"; // Use _longjmp on systems that support it!
1793 Out << "longjmp(*(jmp_buf*)";
1794 writeOperand(I.getOperand(1));
1796 writeOperand(I.getOperand(2));
1799 case Intrinsic::prefetch:
1800 Out << "LLVM_PREFETCH((const void *)";
1801 writeOperand(I.getOperand(1));
1803 writeOperand(I.getOperand(2));
1805 writeOperand(I.getOperand(3));
1808 case Intrinsic::dbg_stoppoint: {
1809 // If we use writeOperand directly we get a "u" suffix which is rejected
1811 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1815 << " \"" << SPI.getDirectory()
1816 << SPI.getFileName() << "\"\n";
1822 Value *Callee = I.getCalledValue();
1824 // If this is a call to a struct-return function, assign to the first
1825 // parameter instead of passing it to the call.
1826 bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
1829 writeOperand(I.getOperand(1));
1833 if (I.isTailCall()) Out << " /*tail*/ ";
1835 const PointerType *PTy = cast<PointerType>(Callee->getType());
1836 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1839 // If this is an indirect call to a struct return function, we need to cast
1841 bool NeedsCast = isStructRet && !isa<Function>(Callee);
1843 // GCC is a real PITA. It does not permit codegening casts of functions to
1844 // function pointers if they are in a call (it generates a trap instruction
1845 // instead!). We work around this by inserting a cast to void* in between
1846 // the function and the function pointer cast. Unfortunately, we can't just
1847 // form the constant expression here, because the folder will immediately
1850 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1851 // that void* and function pointers have the same size. :( To deal with this
1852 // in the common case, we handle casts where the number of arguments passed
1855 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1856 if (CE->getOpcode() == Instruction::Cast)
1857 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1863 // Ok, just cast the pointer type.
1866 printType(Out, I.getCalledValue()->getType());
1868 printStructReturnPointerFunctionType(Out,
1869 cast<PointerType>(I.getCalledValue()->getType()));
1872 writeOperand(Callee);
1873 if (NeedsCast) Out << ')';
1878 unsigned NumDeclaredParams = FTy->getNumParams();
1880 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1882 if (isStructRet) { // Skip struct return argument.
1887 bool PrintedArg = false;
1888 for (; AI != AE; ++AI, ++ArgNo) {
1889 if (PrintedArg) Out << ", ";
1890 if (ArgNo < NumDeclaredParams &&
1891 (*AI)->getType() != FTy->getParamType(ArgNo)) {
1893 printType(Out, FTy->getParamType(ArgNo));
1902 void CWriter::visitMallocInst(MallocInst &I) {
1903 assert(0 && "lowerallocations pass didn't work!");
1906 void CWriter::visitAllocaInst(AllocaInst &I) {
1908 printType(Out, I.getType());
1909 Out << ") alloca(sizeof(";
1910 printType(Out, I.getType()->getElementType());
1912 if (I.isArrayAllocation()) {
1914 writeOperand(I.getOperand(0));
1919 void CWriter::visitFreeInst(FreeInst &I) {
1920 assert(0 && "lowerallocations pass didn't work!");
1923 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1924 gep_type_iterator E) {
1925 bool HasImplicitAddress = false;
1926 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1927 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1928 HasImplicitAddress = true;
1929 } else if (isDirectAlloca(Ptr)) {
1930 HasImplicitAddress = true;
1934 if (!HasImplicitAddress)
1935 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1937 writeOperandInternal(Ptr);
1941 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1942 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1945 writeOperandInternal(Ptr);
1947 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1949 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1952 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1953 "Can only have implicit address with direct accessing");
1955 if (HasImplicitAddress) {
1957 } else if (CI && CI->isNullValue()) {
1958 gep_type_iterator TmpI = I; ++TmpI;
1960 // Print out the -> operator if possible...
1961 if (TmpI != E && isa<StructType>(*TmpI)) {
1962 Out << (HasImplicitAddress ? "." : "->");
1963 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1969 if (isa<StructType>(*I)) {
1970 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1973 writeOperand(I.getOperand());
1978 void CWriter::visitLoadInst(LoadInst &I) {
1980 if (I.isVolatile()) {
1982 printType(Out, I.getType(), "volatile*");
1986 writeOperand(I.getOperand(0));
1992 void CWriter::visitStoreInst(StoreInst &I) {
1994 if (I.isVolatile()) {
1996 printType(Out, I.getOperand(0)->getType(), " volatile*");
1999 writeOperand(I.getPointerOperand());
2000 if (I.isVolatile()) Out << ')';
2002 writeOperand(I.getOperand(0));
2005 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2007 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2011 void CWriter::visitVAArgInst(VAArgInst &I) {
2012 Out << "va_arg(*(va_list*)";
2013 writeOperand(I.getOperand(0));
2015 printType(Out, I.getType());
2019 //===----------------------------------------------------------------------===//
2020 // External Interface declaration
2021 //===----------------------------------------------------------------------===//
2023 bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
2024 CodeGenFileType FileType, bool Fast) {
2025 if (FileType != TargetMachine::AssemblyFile) return true;
2027 PM.add(createLowerGCPass());
2028 PM.add(createLowerAllocationsPass(true));
2029 PM.add(createLowerInvokePass());
2030 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
2031 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2032 PM.add(new CWriter(o));