Added llvmgcc version to allow tests to be xfailed by frontend version.
[llvm-complete.git] / lib / Target / CBackend / Writer.cpp
blob4e86c6fec0d576ec79d0e981396b6a35ee98ef8e
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library converts LLVM code to C code, compilable by GCC and other C
11 // compilers.
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/IntrinsicInst.h"
25 #include "llvm/Analysis/ConstantsScanner.h"
26 #include "llvm/Analysis/FindUsedTypes.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Target/TargetMachineRegistry.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/InstVisitor.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Config/config.h"
41 #include <algorithm>
42 #include <iostream>
43 #include <ios>
44 #include <sstream>
45 using namespace llvm;
47 namespace {
48 // Register the target.
49 RegisterTarget<CTargetMachine> X("c", " C backend");
51 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
52 /// any unnamed structure types that are used by the program, and merges
53 /// external functions with the same name.
54 ///
55 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
56 void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired<FindUsedTypes>();
60 virtual const char *getPassName() const {
61 return "C backend type canonicalizer";
64 virtual bool runOnModule(Module &M);
67 /// CWriter - This class is the main chunk of code that converts an LLVM
68 /// module to a C translation unit.
69 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
70 std::ostream &Out;
71 DefaultIntrinsicLowering IL;
72 Mangler *Mang;
73 LoopInfo *LI;
74 const Module *TheModule;
75 std::map<const Type *, std::string> TypeNames;
77 std::map<const ConstantFP *, unsigned> FPConstantMap;
78 public:
79 CWriter(std::ostream &o) : Out(o) {}
81 virtual const char *getPassName() const { return "C backend"; }
83 void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequired<LoopInfo>();
85 AU.setPreservesAll();
88 virtual bool doInitialization(Module &M);
90 bool runOnFunction(Function &F) {
91 LI = &getAnalysis<LoopInfo>();
93 // Get rid of intrinsics we can't handle.
94 lowerIntrinsics(F);
96 // Output all floating point constants that cannot be printed accurately.
97 printFloatingPointConstants(F);
99 // Ensure that no local symbols conflict with global symbols.
100 F.renameLocalSymbols();
102 printFunction(F);
103 FPConstantMap.clear();
104 return false;
107 virtual bool doFinalization(Module &M) {
108 // Free memory...
109 delete Mang;
110 TypeNames.clear();
111 return false;
114 std::ostream &printType(std::ostream &Out, const Type *Ty,
115 const std::string &VariableName = "",
116 bool IgnoreName = false);
118 void writeOperand(Value *Operand);
119 void writeOperandInternal(Value *Operand);
121 private :
122 void lowerIntrinsics(Function &F);
124 void printModule(Module *M);
125 void printModuleTypes(const SymbolTable &ST);
126 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
127 void printFloatingPointConstants(Function &F);
128 void printFunctionSignature(const Function *F, bool Prototype);
130 void printFunction(Function &);
131 void printBasicBlock(BasicBlock *BB);
132 void printLoop(Loop *L);
134 void printConstant(Constant *CPV);
135 void printConstantArray(ConstantArray *CPA);
136 void printConstantPacked(ConstantPacked *CP);
138 // isInlinableInst - Attempt to inline instructions into their uses to build
139 // trees as much as possible. To do this, we have to consistently decide
140 // what is acceptable to inline, so that variable declarations don't get
141 // printed and an extra copy of the expr is not emitted.
143 static bool isInlinableInst(const Instruction &I) {
144 // Always inline setcc instructions, even if they are shared by multiple
145 // expressions. GCC generates horrible code if we don't.
146 if (isa<SetCondInst>(I)) return true;
148 // Must be an expression, must be used exactly once. If it is dead, we
149 // emit it inline where it would go.
150 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
151 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
152 isa<LoadInst>(I) || isa<VAArgInst>(I))
153 // Don't inline a load across a store or other bad things!
154 return false;
156 // Only inline instruction it it's use is in the same BB as the inst.
157 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
160 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
161 // variables which are accessed with the & operator. This causes GCC to
162 // generate significantly better code than to emit alloca calls directly.
164 static const AllocaInst *isDirectAlloca(const Value *V) {
165 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
166 if (!AI) return false;
167 if (AI->isArrayAllocation())
168 return 0; // FIXME: we can also inline fixed size array allocas!
169 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
170 return 0;
171 return AI;
174 // Instruction visitation functions
175 friend class InstVisitor<CWriter>;
177 void visitReturnInst(ReturnInst &I);
178 void visitBranchInst(BranchInst &I);
179 void visitSwitchInst(SwitchInst &I);
180 void visitInvokeInst(InvokeInst &I) {
181 assert(0 && "Lowerinvoke pass didn't work!");
184 void visitUnwindInst(UnwindInst &I) {
185 assert(0 && "Lowerinvoke pass didn't work!");
187 void visitUnreachableInst(UnreachableInst &I);
189 void visitPHINode(PHINode &I);
190 void visitBinaryOperator(Instruction &I);
192 void visitCastInst (CastInst &I);
193 void visitSelectInst(SelectInst &I);
194 void visitCallInst (CallInst &I);
195 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
197 void visitMallocInst(MallocInst &I);
198 void visitAllocaInst(AllocaInst &I);
199 void visitFreeInst (FreeInst &I);
200 void visitLoadInst (LoadInst &I);
201 void visitStoreInst (StoreInst &I);
202 void visitGetElementPtrInst(GetElementPtrInst &I);
203 void visitVAArgInst (VAArgInst &I);
205 void visitInstruction(Instruction &I) {
206 std::cerr << "C Writer does not know about " << I;
207 abort();
210 void outputLValue(Instruction *I) {
211 Out << " " << Mang->getValueName(I) << " = ";
214 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
215 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
216 BasicBlock *Successor, unsigned Indent);
217 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
218 unsigned Indent);
219 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
220 gep_type_iterator E);
224 /// This method inserts names for any unnamed structure types that are used by
225 /// the program, and removes names from structure types that are not used by the
226 /// program.
228 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
229 // Get a set of types that are used by the program...
230 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
232 // Loop over the module symbol table, removing types from UT that are
233 // already named, and removing names for types that are not used.
235 SymbolTable &MST = M.getSymbolTable();
236 for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
237 TI != TE; ) {
238 SymbolTable::type_iterator I = TI++;
240 // If this is not used, remove it from the symbol table.
241 std::set<const Type *>::iterator UTI = UT.find(I->second);
242 if (UTI == UT.end())
243 MST.remove(I);
244 else
245 UT.erase(UTI); // Only keep one name for this type.
248 // UT now contains types that are not named. Loop over it, naming
249 // structure types.
251 bool Changed = false;
252 unsigned RenameCounter = 0;
253 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
254 I != E; ++I)
255 if (const StructType *ST = dyn_cast<StructType>(*I)) {
256 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
257 ++RenameCounter;
258 Changed = true;
262 // Loop over all external functions and globals. If we have two with
263 // identical names, merge them.
264 // FIXME: This code should disappear when we don't allow values with the same
265 // names when they have different types!
266 std::map<std::string, GlobalValue*> ExtSymbols;
267 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
268 Function *GV = I++;
269 if (GV->isExternal() && GV->hasName()) {
270 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
271 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
272 if (!X.second) {
273 // Found a conflict, replace this global with the previous one.
274 GlobalValue *OldGV = X.first->second;
275 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
276 GV->eraseFromParent();
277 Changed = true;
281 // Do the same for globals.
282 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
283 I != E;) {
284 GlobalVariable *GV = I++;
285 if (GV->isExternal() && GV->hasName()) {
286 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
287 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
288 if (!X.second) {
289 // Found a conflict, replace this global with the previous one.
290 GlobalValue *OldGV = X.first->second;
291 GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
292 GV->eraseFromParent();
293 Changed = true;
298 return Changed;
302 // Pass the Type* and the variable name and this prints out the variable
303 // declaration.
305 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
306 const std::string &NameSoFar,
307 bool IgnoreName) {
308 if (Ty->isPrimitiveType())
309 switch (Ty->getTypeID()) {
310 case Type::VoidTyID: return Out << "void " << NameSoFar;
311 case Type::BoolTyID: return Out << "bool " << NameSoFar;
312 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
313 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
314 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
315 case Type::ShortTyID: return Out << "short " << NameSoFar;
316 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
317 case Type::IntTyID: return Out << "int " << NameSoFar;
318 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
319 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
320 case Type::FloatTyID: return Out << "float " << NameSoFar;
321 case Type::DoubleTyID: return Out << "double " << NameSoFar;
322 default :
323 std::cerr << "Unknown primitive type: " << *Ty << "\n";
324 abort();
327 // Check to see if the type is named.
328 if (!IgnoreName || isa<OpaqueType>(Ty)) {
329 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
330 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
333 switch (Ty->getTypeID()) {
334 case Type::FunctionTyID: {
335 const FunctionType *MTy = cast<FunctionType>(Ty);
336 std::stringstream FunctionInnards;
337 FunctionInnards << " (" << NameSoFar << ") (";
338 for (FunctionType::param_iterator I = MTy->param_begin(),
339 E = MTy->param_end(); I != E; ++I) {
340 if (I != MTy->param_begin())
341 FunctionInnards << ", ";
342 printType(FunctionInnards, *I, "");
344 if (MTy->isVarArg()) {
345 if (MTy->getNumParams())
346 FunctionInnards << ", ...";
347 } else if (!MTy->getNumParams()) {
348 FunctionInnards << "void";
350 FunctionInnards << ')';
351 std::string tstr = FunctionInnards.str();
352 printType(Out, MTy->getReturnType(), tstr);
353 return Out;
355 case Type::StructTyID: {
356 const StructType *STy = cast<StructType>(Ty);
357 Out << NameSoFar + " {\n";
358 unsigned Idx = 0;
359 for (StructType::element_iterator I = STy->element_begin(),
360 E = STy->element_end(); I != E; ++I) {
361 Out << " ";
362 printType(Out, *I, "field" + utostr(Idx++));
363 Out << ";\n";
365 return Out << '}';
368 case Type::PointerTyID: {
369 const PointerType *PTy = cast<PointerType>(Ty);
370 std::string ptrName = "*" + NameSoFar;
372 if (isa<ArrayType>(PTy->getElementType()) ||
373 isa<PackedType>(PTy->getElementType()))
374 ptrName = "(" + ptrName + ")";
376 return printType(Out, PTy->getElementType(), ptrName);
379 case Type::ArrayTyID: {
380 const ArrayType *ATy = cast<ArrayType>(Ty);
381 unsigned NumElements = ATy->getNumElements();
382 if (NumElements == 0) NumElements = 1;
383 return printType(Out, ATy->getElementType(),
384 NameSoFar + "[" + utostr(NumElements) + "]");
387 case Type::PackedTyID: {
388 const PackedType *PTy = cast<PackedType>(Ty);
389 unsigned NumElements = PTy->getNumElements();
390 if (NumElements == 0) NumElements = 1;
391 return printType(Out, PTy->getElementType(),
392 NameSoFar + "[" + utostr(NumElements) + "]");
395 case Type::OpaqueTyID: {
396 static int Count = 0;
397 std::string TyName = "struct opaque_" + itostr(Count++);
398 assert(TypeNames.find(Ty) == TypeNames.end());
399 TypeNames[Ty] = TyName;
400 return Out << TyName << ' ' << NameSoFar;
402 default:
403 assert(0 && "Unhandled case in getTypeProps!");
404 abort();
407 return Out;
410 void CWriter::printConstantArray(ConstantArray *CPA) {
412 // As a special case, print the array as a string if it is an array of
413 // ubytes or an array of sbytes with positive values.
415 const Type *ETy = CPA->getType()->getElementType();
416 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
418 // Make sure the last character is a null char, as automatically added by C
419 if (isString && (CPA->getNumOperands() == 0 ||
420 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
421 isString = false;
423 if (isString) {
424 Out << '\"';
425 // Keep track of whether the last number was a hexadecimal escape
426 bool LastWasHex = false;
428 // Do not include the last character, which we know is null
429 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
430 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
432 // Print it out literally if it is a printable character. The only thing
433 // to be careful about is when the last letter output was a hex escape
434 // code, in which case we have to be careful not to print out hex digits
435 // explicitly (the C compiler thinks it is a continuation of the previous
436 // character, sheesh...)
438 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
439 LastWasHex = false;
440 if (C == '"' || C == '\\')
441 Out << "\\" << C;
442 else
443 Out << C;
444 } else {
445 LastWasHex = false;
446 switch (C) {
447 case '\n': Out << "\\n"; break;
448 case '\t': Out << "\\t"; break;
449 case '\r': Out << "\\r"; break;
450 case '\v': Out << "\\v"; break;
451 case '\a': Out << "\\a"; break;
452 case '\"': Out << "\\\""; break;
453 case '\'': Out << "\\\'"; break;
454 default:
455 Out << "\\x";
456 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
457 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
458 LastWasHex = true;
459 break;
463 Out << '\"';
464 } else {
465 Out << '{';
466 if (CPA->getNumOperands()) {
467 Out << ' ';
468 printConstant(cast<Constant>(CPA->getOperand(0)));
469 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
470 Out << ", ";
471 printConstant(cast<Constant>(CPA->getOperand(i)));
474 Out << " }";
478 void CWriter::printConstantPacked(ConstantPacked *CP) {
479 Out << '{';
480 if (CP->getNumOperands()) {
481 Out << ' ';
482 printConstant(cast<Constant>(CP->getOperand(0)));
483 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
484 Out << ", ";
485 printConstant(cast<Constant>(CP->getOperand(i)));
488 Out << " }";
491 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
492 // textually as a double (rather than as a reference to a stack-allocated
493 // variable). We decide this by converting CFP to a string and back into a
494 // double, and then checking whether the conversion results in a bit-equal
495 // double to the original value of CFP. This depends on us and the target C
496 // compiler agreeing on the conversion process (which is pretty likely since we
497 // only deal in IEEE FP).
499 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
500 #if HAVE_PRINTF_A
501 char Buffer[100];
502 sprintf(Buffer, "%a", CFP->getValue());
504 if (!strncmp(Buffer, "0x", 2) ||
505 !strncmp(Buffer, "-0x", 3) ||
506 !strncmp(Buffer, "+0x", 3))
507 return atof(Buffer) == CFP->getValue();
508 return false;
509 #else
510 std::string StrVal = ftostr(CFP->getValue());
512 while (StrVal[0] == ' ')
513 StrVal.erase(StrVal.begin());
515 // Check to make sure that the stringized number is not some string like "Inf"
516 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
517 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
518 ((StrVal[0] == '-' || StrVal[0] == '+') &&
519 (StrVal[1] >= '0' && StrVal[1] <= '9')))
520 // Reparse stringized version!
521 return atof(StrVal.c_str()) == CFP->getValue();
522 return false;
523 #endif
526 // printConstant - The LLVM Constant to C Constant converter.
527 void CWriter::printConstant(Constant *CPV) {
528 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
529 switch (CE->getOpcode()) {
530 case Instruction::Cast:
531 Out << "((";
532 printType(Out, CPV->getType());
533 Out << ')';
534 printConstant(CE->getOperand(0));
535 Out << ')';
536 return;
538 case Instruction::GetElementPtr:
539 Out << "(&(";
540 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
541 gep_type_end(CPV));
542 Out << "))";
543 return;
544 case Instruction::Select:
545 Out << '(';
546 printConstant(CE->getOperand(0));
547 Out << '?';
548 printConstant(CE->getOperand(1));
549 Out << ':';
550 printConstant(CE->getOperand(2));
551 Out << ')';
552 return;
553 case Instruction::Add:
554 case Instruction::Sub:
555 case Instruction::Mul:
556 case Instruction::Div:
557 case Instruction::Rem:
558 case Instruction::And:
559 case Instruction::Or:
560 case Instruction::Xor:
561 case Instruction::SetEQ:
562 case Instruction::SetNE:
563 case Instruction::SetLT:
564 case Instruction::SetLE:
565 case Instruction::SetGT:
566 case Instruction::SetGE:
567 case Instruction::Shl:
568 case Instruction::Shr:
569 Out << '(';
570 printConstant(CE->getOperand(0));
571 switch (CE->getOpcode()) {
572 case Instruction::Add: Out << " + "; break;
573 case Instruction::Sub: Out << " - "; break;
574 case Instruction::Mul: Out << " * "; break;
575 case Instruction::Div: Out << " / "; break;
576 case Instruction::Rem: Out << " % "; break;
577 case Instruction::And: Out << " & "; break;
578 case Instruction::Or: Out << " | "; break;
579 case Instruction::Xor: Out << " ^ "; break;
580 case Instruction::SetEQ: Out << " == "; break;
581 case Instruction::SetNE: Out << " != "; break;
582 case Instruction::SetLT: Out << " < "; break;
583 case Instruction::SetLE: Out << " <= "; break;
584 case Instruction::SetGT: Out << " > "; break;
585 case Instruction::SetGE: Out << " >= "; break;
586 case Instruction::Shl: Out << " << "; break;
587 case Instruction::Shr: Out << " >> "; break;
588 default: assert(0 && "Illegal opcode here!");
590 printConstant(CE->getOperand(1));
591 Out << ')';
592 return;
594 default:
595 std::cerr << "CWriter Error: Unhandled constant expression: "
596 << *CE << "\n";
597 abort();
599 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
600 Out << "((";
601 printType(Out, CPV->getType());
602 Out << ")/*UNDEF*/0)";
603 return;
606 switch (CPV->getType()->getTypeID()) {
607 case Type::BoolTyID:
608 Out << (CPV == ConstantBool::False ? '0' : '1'); break;
609 case Type::SByteTyID:
610 case Type::ShortTyID:
611 Out << cast<ConstantSInt>(CPV)->getValue(); break;
612 case Type::IntTyID:
613 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
614 Out << "((int)0x80000000U)"; // Handle MININT specially to avoid warning
615 else
616 Out << cast<ConstantSInt>(CPV)->getValue();
617 break;
619 case Type::LongTyID:
620 if (cast<ConstantSInt>(CPV)->isMinValue())
621 Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
622 else
623 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
625 case Type::UByteTyID:
626 case Type::UShortTyID:
627 Out << cast<ConstantUInt>(CPV)->getValue(); break;
628 case Type::UIntTyID:
629 Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
630 case Type::ULongTyID:
631 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
633 case Type::FloatTyID:
634 case Type::DoubleTyID: {
635 ConstantFP *FPC = cast<ConstantFP>(CPV);
636 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
637 if (I != FPConstantMap.end()) {
638 // Because of FP precision problems we must load from a stack allocated
639 // value that holds the value in hex.
640 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
641 << "*)&FPConstant" << I->second << ')';
642 } else {
643 if (IsNAN(FPC->getValue())) {
644 // The value is NaN
646 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
647 // it's 0x7ff4.
648 const unsigned long QuietNaN = 0x7ff8UL;
649 const unsigned long SignalNaN = 0x7ff4UL;
651 // We need to grab the first part of the FP #
652 char Buffer[100];
654 uint64_t ll = DoubleToBits(FPC->getValue());
655 sprintf(Buffer, "0x%llx", (unsigned long long)ll);
657 std::string Num(&Buffer[0], &Buffer[6]);
658 unsigned long Val = strtoul(Num.c_str(), 0, 16);
660 if (FPC->getType() == Type::FloatTy)
661 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
662 << Buffer << "\") /*nan*/ ";
663 else
664 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
665 << Buffer << "\") /*nan*/ ";
666 } else if (IsInf(FPC->getValue())) {
667 // The value is Inf
668 if (FPC->getValue() < 0) Out << '-';
669 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
670 << " /*inf*/ ";
671 } else {
672 std::string Num;
673 #if HAVE_PRINTF_A
674 // Print out the constant as a floating point number.
675 char Buffer[100];
676 sprintf(Buffer, "%a", FPC->getValue());
677 Num = Buffer;
678 #else
679 Num = ftostr(FPC->getValue());
680 #endif
681 Out << Num;
684 break;
687 case Type::ArrayTyID:
688 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
689 const ArrayType *AT = cast<ArrayType>(CPV->getType());
690 Out << '{';
691 if (AT->getNumElements()) {
692 Out << ' ';
693 Constant *CZ = Constant::getNullValue(AT->getElementType());
694 printConstant(CZ);
695 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
696 Out << ", ";
697 printConstant(CZ);
700 Out << " }";
701 } else {
702 printConstantArray(cast<ConstantArray>(CPV));
704 break;
706 case Type::PackedTyID:
707 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
708 const PackedType *AT = cast<PackedType>(CPV->getType());
709 Out << '{';
710 if (AT->getNumElements()) {
711 Out << ' ';
712 Constant *CZ = Constant::getNullValue(AT->getElementType());
713 printConstant(CZ);
714 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
715 Out << ", ";
716 printConstant(CZ);
719 Out << " }";
720 } else {
721 printConstantPacked(cast<ConstantPacked>(CPV));
723 break;
725 case Type::StructTyID:
726 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
727 const StructType *ST = cast<StructType>(CPV->getType());
728 Out << '{';
729 if (ST->getNumElements()) {
730 Out << ' ';
731 printConstant(Constant::getNullValue(ST->getElementType(0)));
732 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
733 Out << ", ";
734 printConstant(Constant::getNullValue(ST->getElementType(i)));
737 Out << " }";
738 } else {
739 Out << '{';
740 if (CPV->getNumOperands()) {
741 Out << ' ';
742 printConstant(cast<Constant>(CPV->getOperand(0)));
743 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
744 Out << ", ";
745 printConstant(cast<Constant>(CPV->getOperand(i)));
748 Out << " }";
750 break;
752 case Type::PointerTyID:
753 if (isa<ConstantPointerNull>(CPV)) {
754 Out << "((";
755 printType(Out, CPV->getType());
756 Out << ")/*NULL*/0)";
757 break;
758 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
759 writeOperand(GV);
760 break;
762 // FALL THROUGH
763 default:
764 std::cerr << "Unknown constant type: " << *CPV << "\n";
765 abort();
769 void CWriter::writeOperandInternal(Value *Operand) {
770 if (Instruction *I = dyn_cast<Instruction>(Operand))
771 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
772 // Should we inline this instruction to build a tree?
773 Out << '(';
774 visit(*I);
775 Out << ')';
776 return;
779 Constant* CPV = dyn_cast<Constant>(Operand);
780 if (CPV && !isa<GlobalValue>(CPV)) {
781 printConstant(CPV);
782 } else {
783 Out << Mang->getValueName(Operand);
787 void CWriter::writeOperand(Value *Operand) {
788 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
789 Out << "(&"; // Global variables are references as their addresses by llvm
791 writeOperandInternal(Operand);
793 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
794 Out << ')';
797 // generateCompilerSpecificCode - This is where we add conditional compilation
798 // directives to cater to specific compilers as need be.
800 static void generateCompilerSpecificCode(std::ostream& Out) {
801 // Alloca is hard to get, and we don't want to include stdlib.h here.
802 Out << "/* get a declaration for alloca */\n"
803 << "#if defined(__CYGWIN__)\n"
804 << "extern void *_alloca(unsigned long);\n"
805 << "#define alloca(x) _alloca(x)\n"
806 << "#elif defined(__APPLE__)\n"
807 << "extern void *__builtin_alloca(unsigned long);\n"
808 << "#define alloca(x) __builtin_alloca(x)\n"
809 << "#elif defined(__sun__)\n"
810 << "#if defined(__sparcv9)\n"
811 << "extern void *__builtin_alloca(unsigned long);\n"
812 << "#else\n"
813 << "extern void *__builtin_alloca(unsigned int);\n"
814 << "#endif\n"
815 << "#define alloca(x) __builtin_alloca(x)\n"
816 << "#elif defined(__FreeBSD__)\n"
817 << "#define alloca(x) __builtin_alloca(x)\n"
818 << "#elif !defined(_MSC_VER)\n"
819 << "#include <alloca.h>\n"
820 << "#endif\n\n";
822 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
823 // If we aren't being compiled with GCC, just drop these attributes.
824 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
825 << "#define __attribute__(X)\n"
826 << "#endif\n\n";
828 #if 0
829 // At some point, we should support "external weak" vs. "weak" linkages.
830 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
831 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
832 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
833 << "#elif defined(__GNUC__)\n"
834 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
835 << "#else\n"
836 << "#define __EXTERNAL_WEAK__\n"
837 << "#endif\n\n";
838 #endif
840 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
841 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
842 << "#define __ATTRIBUTE_WEAK__\n"
843 << "#elif defined(__GNUC__)\n"
844 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
845 << "#else\n"
846 << "#define __ATTRIBUTE_WEAK__\n"
847 << "#endif\n\n";
849 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
850 // From the GCC documentation:
852 // double __builtin_nan (const char *str)
854 // This is an implementation of the ISO C99 function nan.
856 // Since ISO C99 defines this function in terms of strtod, which we do
857 // not implement, a description of the parsing is in order. The string is
858 // parsed as by strtol; that is, the base is recognized by leading 0 or
859 // 0x prefixes. The number parsed is placed in the significand such that
860 // the least significant bit of the number is at the least significant
861 // bit of the significand. The number is truncated to fit the significand
862 // field provided. The significand is forced to be a quiet NaN.
864 // This function, if given a string literal, is evaluated early enough
865 // that it is considered a compile-time constant.
867 // float __builtin_nanf (const char *str)
869 // Similar to __builtin_nan, except the return type is float.
871 // double __builtin_inf (void)
873 // Similar to __builtin_huge_val, except a warning is generated if the
874 // target floating-point format does not support infinities. This
875 // function is suitable for implementing the ISO C99 macro INFINITY.
877 // float __builtin_inff (void)
879 // Similar to __builtin_inf, except the return type is float.
880 Out << "#ifdef __GNUC__\n"
881 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
882 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
883 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
884 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
885 << "#define LLVM_INF __builtin_inf() /* Double */\n"
886 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
887 << "#define LLVM_PREFETCH(addr,rw,locality) "
888 "__builtin_prefetch(addr,rw,locality)\n"
889 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
890 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
891 << "#else\n"
892 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
893 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
894 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
895 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
896 << "#define LLVM_INF ((double)0.0) /* Double */\n"
897 << "#define LLVM_INFF 0.0F /* Float */\n"
898 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
899 << "#define __ATTRIBUTE_CTOR__\n"
900 << "#define __ATTRIBUTE_DTOR__\n"
901 << "#endif\n\n";
903 // Output target-specific code that should be inserted into main.
904 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
905 // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
906 Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
907 << "#if defined(i386) || defined(__i386__) || defined(__i386)\n"
908 << "#undef CODE_FOR_MAIN\n"
909 << "#define CODE_FOR_MAIN() \\\n"
910 << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
911 << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
912 << "#endif\n#endif\n";
916 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
917 /// the StaticTors set.
918 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
919 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
920 if (!InitList) return;
922 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
923 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
924 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
926 if (CS->getOperand(1)->isNullValue())
927 return; // Found a null terminator, exit printing.
928 Constant *FP = CS->getOperand(1);
929 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
930 if (CE->getOpcode() == Instruction::Cast)
931 FP = CE->getOperand(0);
932 if (Function *F = dyn_cast<Function>(FP))
933 StaticTors.insert(F);
937 enum SpecialGlobalClass {
938 NotSpecial = 0,
939 GlobalCtors, GlobalDtors,
940 NotPrinted
943 /// getGlobalVariableClass - If this is a global that is specially recognized
944 /// by LLVM, return a code that indicates how we should handle it.
945 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
946 // If this is a global ctors/dtors list, handle it now.
947 if (GV->hasAppendingLinkage() && GV->use_empty()) {
948 if (GV->getName() == "llvm.global_ctors")
949 return GlobalCtors;
950 else if (GV->getName() == "llvm.global_dtors")
951 return GlobalDtors;
954 // Otherwise, it it is other metadata, don't print it. This catches things
955 // like debug information.
956 if (GV->getSection() == "llvm.metadata")
957 return NotPrinted;
959 return NotSpecial;
963 bool CWriter::doInitialization(Module &M) {
964 // Initialize
965 TheModule = &M;
967 IL.AddPrototypes(M);
969 // Ensure that all structure types have names...
970 Mang = new Mangler(M);
971 Mang->markCharUnacceptable('.');
973 // Keep track of which functions are static ctors/dtors so they can have
974 // an attribute added to their prototypes.
975 std::set<Function*> StaticCtors, StaticDtors;
976 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
977 I != E; ++I) {
978 switch (getGlobalVariableClass(I)) {
979 default: break;
980 case GlobalCtors:
981 FindStaticTors(I, StaticCtors);
982 break;
983 case GlobalDtors:
984 FindStaticTors(I, StaticDtors);
985 break;
989 // get declaration for alloca
990 Out << "/* Provide Declarations */\n";
991 Out << "#include <stdarg.h>\n"; // Varargs support
992 Out << "#include <setjmp.h>\n"; // Unwind support
993 generateCompilerSpecificCode(Out);
995 // Provide a definition for `bool' if not compiling with a C++ compiler.
996 Out << "\n"
997 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
999 << "\n\n/* Support for floating point constants */\n"
1000 << "typedef unsigned long long ConstantDoubleTy;\n"
1001 << "typedef unsigned int ConstantFloatTy;\n"
1003 << "\n\n/* Global Declarations */\n";
1005 // First output all the declarations for the program, because C requires
1006 // Functions & globals to be declared before they are used.
1009 // Loop over the symbol table, emitting all named constants...
1010 printModuleTypes(M.getSymbolTable());
1012 // Global variable declarations...
1013 if (!M.global_empty()) {
1014 Out << "\n/* External Global Variable Declarations */\n";
1015 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1016 I != E; ++I) {
1017 if (I->hasExternalLinkage()) {
1018 Out << "extern ";
1019 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1020 Out << ";\n";
1025 // Function declarations
1026 Out << "\n/* Function Declarations */\n";
1027 Out << "double fmod(double, double);\n"; // Support for FP rem
1028 Out << "float fmodf(float, float);\n";
1030 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1031 // Don't print declarations for intrinsic functions.
1032 if (!I->getIntrinsicID() &&
1033 I->getName() != "setjmp" && I->getName() != "longjmp") {
1034 printFunctionSignature(I, true);
1035 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1036 Out << " __ATTRIBUTE_WEAK__";
1037 if (StaticCtors.count(I))
1038 Out << " __ATTRIBUTE_CTOR__";
1039 if (StaticDtors.count(I))
1040 Out << " __ATTRIBUTE_DTOR__";
1041 Out << ";\n";
1045 // Output the global variable declarations
1046 if (!M.global_empty()) {
1047 Out << "\n\n/* Global Variable Declarations */\n";
1048 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1049 I != E; ++I)
1050 if (!I->isExternal()) {
1051 // Ignore special globals, such as debug info.
1052 if (getGlobalVariableClass(I))
1053 continue;
1055 if (I->hasInternalLinkage())
1056 Out << "static ";
1057 else
1058 Out << "extern ";
1059 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1061 if (I->hasLinkOnceLinkage())
1062 Out << " __attribute__((common))";
1063 else if (I->hasWeakLinkage())
1064 Out << " __ATTRIBUTE_WEAK__";
1065 Out << ";\n";
1069 // Output the global variable definitions and contents...
1070 if (!M.global_empty()) {
1071 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1072 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1073 I != E; ++I)
1074 if (!I->isExternal()) {
1075 // Ignore special globals, such as debug info.
1076 if (getGlobalVariableClass(I))
1077 continue;
1079 if (I->hasInternalLinkage())
1080 Out << "static ";
1081 printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1082 if (I->hasLinkOnceLinkage())
1083 Out << " __attribute__((common))";
1084 else if (I->hasWeakLinkage())
1085 Out << " __ATTRIBUTE_WEAK__";
1087 // If the initializer is not null, emit the initializer. If it is null,
1088 // we try to avoid emitting large amounts of zeros. The problem with
1089 // this, however, occurs when the variable has weak linkage. In this
1090 // case, the assembler will complain about the variable being both weak
1091 // and common, so we disable this optimization.
1092 if (!I->getInitializer()->isNullValue()) {
1093 Out << " = " ;
1094 writeOperand(I->getInitializer());
1095 } else if (I->hasWeakLinkage()) {
1096 // We have to specify an initializer, but it doesn't have to be
1097 // complete. If the value is an aggregate, print out { 0 }, and let
1098 // the compiler figure out the rest of the zeros.
1099 Out << " = " ;
1100 if (isa<StructType>(I->getInitializer()->getType()) ||
1101 isa<ArrayType>(I->getInitializer()->getType()) ||
1102 isa<PackedType>(I->getInitializer()->getType())) {
1103 Out << "{ 0 }";
1104 } else {
1105 // Just print it out normally.
1106 writeOperand(I->getInitializer());
1109 Out << ";\n";
1113 if (!M.empty())
1114 Out << "\n\n/* Function Bodies */\n";
1115 return false;
1119 /// Output all floating point constants that cannot be printed accurately...
1120 void CWriter::printFloatingPointConstants(Function &F) {
1121 // Scan the module for floating point constants. If any FP constant is used
1122 // in the function, we want to redirect it here so that we do not depend on
1123 // the precision of the printed form, unless the printed form preserves
1124 // precision.
1126 static unsigned FPCounter = 0;
1127 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1128 I != E; ++I)
1129 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1130 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1131 !FPConstantMap.count(FPC)) {
1132 double Val = FPC->getValue();
1134 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1136 if (FPC->getType() == Type::DoubleTy) {
1137 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1138 << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1139 << "ULL; /* " << Val << " */\n";
1140 } else if (FPC->getType() == Type::FloatTy) {
1141 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1142 << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1143 << "U; /* " << Val << " */\n";
1144 } else
1145 assert(0 && "Unknown float type!");
1148 Out << '\n';
1152 /// printSymbolTable - Run through symbol table looking for type names. If a
1153 /// type name is found, emit its declaration...
1155 void CWriter::printModuleTypes(const SymbolTable &ST) {
1156 // We are only interested in the type plane of the symbol table.
1157 SymbolTable::type_const_iterator I = ST.type_begin();
1158 SymbolTable::type_const_iterator End = ST.type_end();
1160 // If there are no type names, exit early.
1161 if (I == End) return;
1163 // Print out forward declarations for structure types before anything else!
1164 Out << "/* Structure forward decls */\n";
1165 for (; I != End; ++I)
1166 if (const Type *STy = dyn_cast<StructType>(I->second)) {
1167 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1168 Out << Name << ";\n";
1169 TypeNames.insert(std::make_pair(STy, Name));
1172 Out << '\n';
1174 // Now we can print out typedefs...
1175 Out << "/* Typedefs */\n";
1176 for (I = ST.type_begin(); I != End; ++I) {
1177 const Type *Ty = cast<Type>(I->second);
1178 std::string Name = "l_" + Mang->makeNameProper(I->first);
1179 Out << "typedef ";
1180 printType(Out, Ty, Name);
1181 Out << ";\n";
1184 Out << '\n';
1186 // Keep track of which structures have been printed so far...
1187 std::set<const StructType *> StructPrinted;
1189 // Loop over all structures then push them into the stack so they are
1190 // printed in the correct order.
1192 Out << "/* Structure contents */\n";
1193 for (I = ST.type_begin(); I != End; ++I)
1194 if (const StructType *STy = dyn_cast<StructType>(I->second))
1195 // Only print out used types!
1196 printContainedStructs(STy, StructPrinted);
1199 // Push the struct onto the stack and recursively push all structs
1200 // this one depends on.
1202 // TODO: Make this work properly with packed types
1204 void CWriter::printContainedStructs(const Type *Ty,
1205 std::set<const StructType*> &StructPrinted){
1206 // Don't walk through pointers.
1207 if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1209 // Print all contained types first.
1210 for (Type::subtype_iterator I = Ty->subtype_begin(),
1211 E = Ty->subtype_end(); I != E; ++I)
1212 printContainedStructs(*I, StructPrinted);
1214 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1215 // Check to see if we have already printed this struct.
1216 if (StructPrinted.insert(STy).second) {
1217 // Print structure type out.
1218 std::string Name = TypeNames[STy];
1219 printType(Out, STy, Name, true);
1220 Out << ";\n\n";
1225 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1226 if (F->hasInternalLinkage()) Out << "static ";
1228 // Loop over the arguments, printing them...
1229 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1231 std::stringstream FunctionInnards;
1233 // Print out the name...
1234 FunctionInnards << Mang->getValueName(F) << '(';
1236 if (!F->isExternal()) {
1237 if (!F->arg_empty()) {
1238 std::string ArgName;
1239 if (F->arg_begin()->hasName() || !Prototype)
1240 ArgName = Mang->getValueName(F->arg_begin());
1241 printType(FunctionInnards, F->arg_begin()->getType(), ArgName);
1242 for (Function::const_arg_iterator I = ++F->arg_begin(), E = F->arg_end();
1243 I != E; ++I) {
1244 FunctionInnards << ", ";
1245 if (I->hasName() || !Prototype)
1246 ArgName = Mang->getValueName(I);
1247 else
1248 ArgName = "";
1249 printType(FunctionInnards, I->getType(), ArgName);
1252 } else {
1253 // Loop over the arguments, printing them...
1254 for (FunctionType::param_iterator I = FT->param_begin(),
1255 E = FT->param_end(); I != E; ++I) {
1256 if (I != FT->param_begin()) FunctionInnards << ", ";
1257 printType(FunctionInnards, *I);
1261 // Finish printing arguments... if this is a vararg function, print the ...,
1262 // unless there are no known types, in which case, we just emit ().
1264 if (FT->isVarArg() && FT->getNumParams()) {
1265 if (FT->getNumParams()) FunctionInnards << ", ";
1266 FunctionInnards << "..."; // Output varargs portion of signature!
1267 } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
1268 FunctionInnards << "void"; // ret() -> ret(void) in C.
1270 FunctionInnards << ')';
1271 // Print out the return type and the entire signature for that matter
1272 printType(Out, F->getReturnType(), FunctionInnards.str());
1275 void CWriter::printFunction(Function &F) {
1276 printFunctionSignature(&F, false);
1277 Out << " {\n";
1279 // print local variable information for the function
1280 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1281 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1282 Out << " ";
1283 printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1284 Out << "; /* Address-exposed local */\n";
1285 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1286 Out << " ";
1287 printType(Out, I->getType(), Mang->getValueName(&*I));
1288 Out << ";\n";
1290 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1291 Out << " ";
1292 printType(Out, I->getType(),
1293 Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1294 Out << ";\n";
1298 Out << '\n';
1300 if (F.hasExternalLinkage() && F.getName() == "main")
1301 Out << " CODE_FOR_MAIN();\n";
1303 // print the basic blocks
1304 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1305 if (Loop *L = LI->getLoopFor(BB)) {
1306 if (L->getHeader() == BB && L->getParentLoop() == 0)
1307 printLoop(L);
1308 } else {
1309 printBasicBlock(BB);
1313 Out << "}\n\n";
1316 void CWriter::printLoop(Loop *L) {
1317 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
1318 << "' to make GCC happy */\n";
1319 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1320 BasicBlock *BB = L->getBlocks()[i];
1321 Loop *BBLoop = LI->getLoopFor(BB);
1322 if (BBLoop == L)
1323 printBasicBlock(BB);
1324 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1325 printLoop(BBLoop);
1327 Out << " } while (1); /* end of syntactic loop '"
1328 << L->getHeader()->getName() << "' */\n";
1331 void CWriter::printBasicBlock(BasicBlock *BB) {
1333 // Don't print the label for the basic block if there are no uses, or if
1334 // the only terminator use is the predecessor basic block's terminator.
1335 // We have to scan the use list because PHI nodes use basic blocks too but
1336 // do not require a label to be generated.
1338 bool NeedsLabel = false;
1339 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1340 if (isGotoCodeNecessary(*PI, BB)) {
1341 NeedsLabel = true;
1342 break;
1345 if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1347 // Output all of the instructions in the basic block...
1348 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1349 ++II) {
1350 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1351 if (II->getType() != Type::VoidTy)
1352 outputLValue(II);
1353 else
1354 Out << " ";
1355 visit(*II);
1356 Out << ";\n";
1360 // Don't emit prefix or suffix for the terminator...
1361 visit(*BB->getTerminator());
1365 // Specific Instruction type classes... note that all of the casts are
1366 // necessary because we use the instruction classes as opaque types...
1368 void CWriter::visitReturnInst(ReturnInst &I) {
1369 // Don't output a void return if this is the last basic block in the function
1370 if (I.getNumOperands() == 0 &&
1371 &*--I.getParent()->getParent()->end() == I.getParent() &&
1372 !I.getParent()->size() == 1) {
1373 return;
1376 Out << " return";
1377 if (I.getNumOperands()) {
1378 Out << ' ';
1379 writeOperand(I.getOperand(0));
1381 Out << ";\n";
1384 void CWriter::visitSwitchInst(SwitchInst &SI) {
1386 Out << " switch (";
1387 writeOperand(SI.getOperand(0));
1388 Out << ") {\n default:\n";
1389 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1390 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1391 Out << ";\n";
1392 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1393 Out << " case ";
1394 writeOperand(SI.getOperand(i));
1395 Out << ":\n";
1396 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1397 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1398 printBranchToBlock(SI.getParent(), Succ, 2);
1399 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1400 Out << " break;\n";
1402 Out << " }\n";
1405 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1406 Out << " /*UNREACHABLE*/;\n";
1409 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1410 /// FIXME: This should be reenabled, but loop reordering safe!!
1411 return true;
1413 if (next(Function::iterator(From)) != Function::iterator(To))
1414 return true; // Not the direct successor, we need a goto.
1416 //isa<SwitchInst>(From->getTerminator())
1418 if (LI->getLoopFor(From) != LI->getLoopFor(To))
1419 return true;
1420 return false;
1423 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1424 BasicBlock *Successor,
1425 unsigned Indent) {
1426 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1427 PHINode *PN = cast<PHINode>(I);
1428 // Now we have to do the printing.
1429 Value *IV = PN->getIncomingValueForBlock(CurBlock);
1430 if (!isa<UndefValue>(IV)) {
1431 Out << std::string(Indent, ' ');
1432 Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1433 writeOperand(IV);
1434 Out << "; /* for PHI node */\n";
1439 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1440 unsigned Indent) {
1441 if (isGotoCodeNecessary(CurBB, Succ)) {
1442 Out << std::string(Indent, ' ') << " goto ";
1443 writeOperand(Succ);
1444 Out << ";\n";
1448 // Branch instruction printing - Avoid printing out a branch to a basic block
1449 // that immediately succeeds the current one.
1451 void CWriter::visitBranchInst(BranchInst &I) {
1453 if (I.isConditional()) {
1454 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1455 Out << " if (";
1456 writeOperand(I.getCondition());
1457 Out << ") {\n";
1459 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1460 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1462 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1463 Out << " } else {\n";
1464 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1465 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1467 } else {
1468 // First goto not necessary, assume second one is...
1469 Out << " if (!";
1470 writeOperand(I.getCondition());
1471 Out << ") {\n";
1473 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1474 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1477 Out << " }\n";
1478 } else {
1479 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1480 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1482 Out << "\n";
1485 // PHI nodes get copied into temporary values at the end of predecessor basic
1486 // blocks. We now need to copy these temporary values into the REAL value for
1487 // the PHI.
1488 void CWriter::visitPHINode(PHINode &I) {
1489 writeOperand(&I);
1490 Out << "__PHI_TEMPORARY";
1494 void CWriter::visitBinaryOperator(Instruction &I) {
1495 // binary instructions, shift instructions, setCond instructions.
1496 assert(!isa<PointerType>(I.getType()));
1498 // We must cast the results of binary operations which might be promoted.
1499 bool needsCast = false;
1500 if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1501 || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1502 || (I.getType() == Type::FloatTy)) {
1503 needsCast = true;
1504 Out << "((";
1505 printType(Out, I.getType());
1506 Out << ")(";
1509 // If this is a negation operation, print it out as such. For FP, we don't
1510 // want to print "-0.0 - X".
1511 if (BinaryOperator::isNeg(&I)) {
1512 Out << "-(";
1513 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1514 Out << ")";
1515 } else if (I.getOpcode() == Instruction::Rem &&
1516 I.getType()->isFloatingPoint()) {
1517 // Output a call to fmod/fmodf instead of emitting a%b
1518 if (I.getType() == Type::FloatTy)
1519 Out << "fmodf(";
1520 else
1521 Out << "fmod(";
1522 writeOperand(I.getOperand(0));
1523 Out << ", ";
1524 writeOperand(I.getOperand(1));
1525 Out << ")";
1526 } else {
1527 writeOperand(I.getOperand(0));
1529 switch (I.getOpcode()) {
1530 case Instruction::Add: Out << " + "; break;
1531 case Instruction::Sub: Out << " - "; break;
1532 case Instruction::Mul: Out << '*'; break;
1533 case Instruction::Div: Out << '/'; break;
1534 case Instruction::Rem: Out << '%'; break;
1535 case Instruction::And: Out << " & "; break;
1536 case Instruction::Or: Out << " | "; break;
1537 case Instruction::Xor: Out << " ^ "; break;
1538 case Instruction::SetEQ: Out << " == "; break;
1539 case Instruction::SetNE: Out << " != "; break;
1540 case Instruction::SetLE: Out << " <= "; break;
1541 case Instruction::SetGE: Out << " >= "; break;
1542 case Instruction::SetLT: Out << " < "; break;
1543 case Instruction::SetGT: Out << " > "; break;
1544 case Instruction::Shl : Out << " << "; break;
1545 case Instruction::Shr : Out << " >> "; break;
1546 default: std::cerr << "Invalid operator type!" << I; abort();
1549 writeOperand(I.getOperand(1));
1552 if (needsCast) {
1553 Out << "))";
1557 void CWriter::visitCastInst(CastInst &I) {
1558 if (I.getType() == Type::BoolTy) {
1559 Out << '(';
1560 writeOperand(I.getOperand(0));
1561 Out << " != 0)";
1562 return;
1564 Out << '(';
1565 printType(Out, I.getType());
1566 Out << ')';
1567 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1568 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1569 // Avoid "cast to pointer from integer of different size" warnings
1570 Out << "(long)";
1573 writeOperand(I.getOperand(0));
1576 void CWriter::visitSelectInst(SelectInst &I) {
1577 Out << "((";
1578 writeOperand(I.getCondition());
1579 Out << ") ? (";
1580 writeOperand(I.getTrueValue());
1581 Out << ") : (";
1582 writeOperand(I.getFalseValue());
1583 Out << "))";
1587 void CWriter::lowerIntrinsics(Function &F) {
1588 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1589 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1590 if (CallInst *CI = dyn_cast<CallInst>(I++))
1591 if (Function *F = CI->getCalledFunction())
1592 switch (F->getIntrinsicID()) {
1593 case Intrinsic::not_intrinsic:
1594 case Intrinsic::vastart:
1595 case Intrinsic::vacopy:
1596 case Intrinsic::vaend:
1597 case Intrinsic::returnaddress:
1598 case Intrinsic::frameaddress:
1599 case Intrinsic::setjmp:
1600 case Intrinsic::longjmp:
1601 case Intrinsic::prefetch:
1602 case Intrinsic::dbg_stoppoint:
1603 // We directly implement these intrinsics
1604 break;
1605 default:
1606 // If this is an intrinsic that directly corresponds to a GCC
1607 // builtin, we handle it.
1608 const char *BuiltinName = "";
1609 #define GET_GCC_BUILTIN_NAME
1610 #include "llvm/Intrinsics.gen"
1611 #undef GET_GCC_BUILTIN_NAME
1612 // If we handle it, don't lower it.
1613 if (BuiltinName[0]) break;
1615 // All other intrinsic calls we must lower.
1616 Instruction *Before = 0;
1617 if (CI != &BB->front())
1618 Before = prior(BasicBlock::iterator(CI));
1620 IL.LowerIntrinsicCall(CI);
1621 if (Before) { // Move iterator to instruction after call
1622 I = Before; ++I;
1623 } else {
1624 I = BB->begin();
1626 break;
1632 void CWriter::visitCallInst(CallInst &I) {
1633 bool WroteCallee = false;
1635 // Handle intrinsic function calls first...
1636 if (Function *F = I.getCalledFunction())
1637 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1638 switch (ID) {
1639 default: {
1640 // If this is an intrinsic that directly corresponds to a GCC
1641 // builtin, we emit it here.
1642 const char *BuiltinName = "";
1643 #define GET_GCC_BUILTIN_NAME
1644 #include "llvm/Intrinsics.gen"
1645 #undef GET_GCC_BUILTIN_NAME
1646 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1648 Out << BuiltinName;
1649 WroteCallee = true;
1650 break;
1652 case Intrinsic::vastart:
1653 Out << "0; ";
1655 Out << "va_start(*(va_list*)";
1656 writeOperand(I.getOperand(1));
1657 Out << ", ";
1658 // Output the last argument to the enclosing function...
1659 if (I.getParent()->getParent()->arg_empty()) {
1660 std::cerr << "The C backend does not currently support zero "
1661 << "argument varargs functions, such as '"
1662 << I.getParent()->getParent()->getName() << "'!\n";
1663 abort();
1665 writeOperand(--I.getParent()->getParent()->arg_end());
1666 Out << ')';
1667 return;
1668 case Intrinsic::vaend:
1669 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
1670 Out << "0; va_end(*(va_list*)";
1671 writeOperand(I.getOperand(1));
1672 Out << ')';
1673 } else {
1674 Out << "va_end(*(va_list*)0)";
1676 return;
1677 case Intrinsic::vacopy:
1678 Out << "0; ";
1679 Out << "va_copy(*(va_list*)";
1680 writeOperand(I.getOperand(1));
1681 Out << ", *(va_list*)";
1682 writeOperand(I.getOperand(2));
1683 Out << ')';
1684 return;
1685 case Intrinsic::returnaddress:
1686 Out << "__builtin_return_address(";
1687 writeOperand(I.getOperand(1));
1688 Out << ')';
1689 return;
1690 case Intrinsic::frameaddress:
1691 Out << "__builtin_frame_address(";
1692 writeOperand(I.getOperand(1));
1693 Out << ')';
1694 return;
1695 case Intrinsic::setjmp:
1696 Out << "setjmp(*(jmp_buf*)";
1697 writeOperand(I.getOperand(1));
1698 Out << ')';
1699 return;
1700 case Intrinsic::longjmp:
1701 Out << "longjmp(*(jmp_buf*)";
1702 writeOperand(I.getOperand(1));
1703 Out << ", ";
1704 writeOperand(I.getOperand(2));
1705 Out << ')';
1706 return;
1707 case Intrinsic::prefetch:
1708 Out << "LLVM_PREFETCH((const void *)";
1709 writeOperand(I.getOperand(1));
1710 Out << ", ";
1711 writeOperand(I.getOperand(2));
1712 Out << ", ";
1713 writeOperand(I.getOperand(3));
1714 Out << ")";
1715 return;
1716 case Intrinsic::dbg_stoppoint: {
1717 // If we use writeOperand directly we get a "u" suffix which is rejected
1718 // by gcc.
1719 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1721 Out << "\n#line "
1722 << SPI.getLine()
1723 << " \"" << SPI.getDirectory()
1724 << SPI.getFileName() << "\"\n";
1725 return;
1730 Value *Callee = I.getCalledValue();
1732 // GCC is really a PITA. It does not permit codegening casts of functions to
1733 // function pointers if they are in a call (it generates a trap instruction
1734 // instead!). We work around this by inserting a cast to void* in between the
1735 // function and the function pointer cast. Unfortunately, we can't just form
1736 // the constant expression here, because the folder will immediately nuke it.
1738 // Note finally, that this is completely unsafe. ANSI C does not guarantee
1739 // that void* and function pointers have the same size. :( To deal with this
1740 // in the common case, we handle casts where the number of arguments passed
1741 // match exactly.
1743 if (I.isTailCall()) Out << " /*tail*/ ";
1744 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1745 if (CE->getOpcode() == Instruction::Cast)
1746 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1747 const FunctionType *RFTy = RF->getFunctionType();
1748 if (RFTy->getNumParams() == I.getNumOperands()-1) {
1749 // If the call site expects a value, and the actual callee doesn't
1750 // provide one, return 0.
1751 if (I.getType() != Type::VoidTy &&
1752 RFTy->getReturnType() == Type::VoidTy)
1753 Out << "0 /*actual callee doesn't return value*/; ";
1754 Callee = RF;
1755 } else {
1756 // Ok, just cast the pointer type.
1757 Out << "((";
1758 printType(Out, CE->getType());
1759 Out << ")(void*)";
1760 printConstant(RF);
1761 Out << ')';
1762 WroteCallee = true;
1766 const PointerType *PTy = cast<PointerType>(Callee->getType());
1767 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1768 const Type *RetTy = FTy->getReturnType();
1770 if (!WroteCallee) writeOperand(Callee);
1771 Out << '(';
1773 unsigned NumDeclaredParams = FTy->getNumParams();
1775 if (I.getNumOperands() != 1) {
1776 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1777 if (NumDeclaredParams && (*AI)->getType() != FTy->getParamType(0)) {
1778 Out << '(';
1779 printType(Out, FTy->getParamType(0));
1780 Out << ')';
1783 writeOperand(*AI);
1785 unsigned ArgNo;
1786 for (ArgNo = 1, ++AI; AI != AE; ++AI, ++ArgNo) {
1787 Out << ", ";
1788 if (ArgNo < NumDeclaredParams &&
1789 (*AI)->getType() != FTy->getParamType(ArgNo)) {
1790 Out << '(';
1791 printType(Out, FTy->getParamType(ArgNo));
1792 Out << ')';
1794 writeOperand(*AI);
1797 Out << ')';
1800 void CWriter::visitMallocInst(MallocInst &I) {
1801 assert(0 && "lowerallocations pass didn't work!");
1804 void CWriter::visitAllocaInst(AllocaInst &I) {
1805 Out << '(';
1806 printType(Out, I.getType());
1807 Out << ") alloca(sizeof(";
1808 printType(Out, I.getType()->getElementType());
1809 Out << ')';
1810 if (I.isArrayAllocation()) {
1811 Out << " * " ;
1812 writeOperand(I.getOperand(0));
1814 Out << ')';
1817 void CWriter::visitFreeInst(FreeInst &I) {
1818 assert(0 && "lowerallocations pass didn't work!");
1821 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1822 gep_type_iterator E) {
1823 bool HasImplicitAddress = false;
1824 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1825 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1826 HasImplicitAddress = true;
1827 } else if (isDirectAlloca(Ptr)) {
1828 HasImplicitAddress = true;
1831 if (I == E) {
1832 if (!HasImplicitAddress)
1833 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1835 writeOperandInternal(Ptr);
1836 return;
1839 const Constant *CI = dyn_cast<Constant>(I.getOperand());
1840 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1841 Out << "(&";
1843 writeOperandInternal(Ptr);
1845 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1846 Out << ')';
1847 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1850 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1851 "Can only have implicit address with direct accessing");
1853 if (HasImplicitAddress) {
1854 ++I;
1855 } else if (CI && CI->isNullValue()) {
1856 gep_type_iterator TmpI = I; ++TmpI;
1858 // Print out the -> operator if possible...
1859 if (TmpI != E && isa<StructType>(*TmpI)) {
1860 Out << (HasImplicitAddress ? "." : "->");
1861 Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1862 I = ++TmpI;
1866 for (; I != E; ++I)
1867 if (isa<StructType>(*I)) {
1868 Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1869 } else {
1870 Out << '[';
1871 writeOperand(I.getOperand());
1872 Out << ']';
1876 void CWriter::visitLoadInst(LoadInst &I) {
1877 Out << '*';
1878 if (I.isVolatile()) {
1879 Out << "((";
1880 printType(Out, I.getType(), "volatile*");
1881 Out << ")";
1884 writeOperand(I.getOperand(0));
1886 if (I.isVolatile())
1887 Out << ')';
1890 void CWriter::visitStoreInst(StoreInst &I) {
1891 Out << '*';
1892 if (I.isVolatile()) {
1893 Out << "((";
1894 printType(Out, I.getOperand(0)->getType(), " volatile*");
1895 Out << ")";
1897 writeOperand(I.getPointerOperand());
1898 if (I.isVolatile()) Out << ')';
1899 Out << " = ";
1900 writeOperand(I.getOperand(0));
1903 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1904 Out << '&';
1905 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1906 gep_type_end(I));
1909 void CWriter::visitVAArgInst(VAArgInst &I) {
1910 Out << "va_arg(*(va_list*)";
1911 writeOperand(I.getOperand(0));
1912 Out << ", ";
1913 printType(Out, I.getType());
1914 Out << ");\n ";
1917 //===----------------------------------------------------------------------===//
1918 // External Interface declaration
1919 //===----------------------------------------------------------------------===//
1921 bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
1922 CodeGenFileType FileType, bool Fast) {
1923 if (FileType != TargetMachine::AssemblyFile) return true;
1925 PM.add(createLowerGCPass());
1926 PM.add(createLowerAllocationsPass(true));
1927 PM.add(createLowerInvokePass());
1928 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
1929 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
1930 PM.add(new CWriter(o));
1931 return false;