1 //===-- CBackend.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/ParameterAttributes.h"
22 #include "llvm/Pass.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Analysis/ConstantsScanner.h"
29 #include "llvm/Analysis/FindUsedTypes.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "llvm/Target/TargetMachineRegistry.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Support/CallSite.h"
37 #include "llvm/Support/CFG.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/InstVisitor.h"
40 #include "llvm/Support/Mangler.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Config/config.h"
51 // Register the target.
52 RegisterTarget<CTargetMachine> X("c", " C backend");
54 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
55 /// any unnamed structure types that are used by the program, and merges
56 /// external functions with the same name.
58 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
61 CBackendNameAllUsedStructsAndMergeFunctions()
62 : ModulePass((intptr_t)&ID) {}
63 void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addRequired<FindUsedTypes>();
67 virtual const char *getPassName() const {
68 return "C backend type canonicalizer";
71 virtual bool runOnModule(Module &M);
74 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
76 /// CWriter - This class is the main chunk of code that converts an LLVM
77 /// module to a C translation unit.
78 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
80 IntrinsicLowering *IL;
83 const Module *TheModule;
84 const TargetAsmInfo* TAsm;
86 std::map<const Type *, std::string> TypeNames;
87 std::map<const ConstantFP *, unsigned> FPConstantMap;
88 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
92 CWriter(std::ostream &o)
93 : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0),
94 TheModule(0), TAsm(0), TD(0) {}
96 virtual const char *getPassName() const { return "C backend"; }
98 void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<LoopInfo>();
100 AU.setPreservesAll();
103 virtual bool doInitialization(Module &M);
105 bool runOnFunction(Function &F) {
106 LI = &getAnalysis<LoopInfo>();
108 // Get rid of intrinsics we can't handle.
111 // Output all floating point constants that cannot be printed accurately.
112 printFloatingPointConstants(F);
115 FPConstantMap.clear();
119 virtual bool doFinalization(Module &M) {
126 std::ostream &printType(std::ostream &Out, const Type *Ty,
127 bool isSigned = false,
128 const std::string &VariableName = "",
129 bool IgnoreName = false,
130 const ParamAttrsList *PAL = 0);
131 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
133 const std::string &NameSoFar = "");
135 void printStructReturnPointerFunctionType(std::ostream &Out,
136 const ParamAttrsList *PAL,
137 const PointerType *Ty);
139 void writeOperand(Value *Operand);
140 void writeOperandRaw(Value *Operand);
141 void writeOperandInternal(Value *Operand);
142 void writeOperandWithCast(Value* Operand, unsigned Opcode);
143 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
144 bool writeInstructionCast(const Instruction &I);
147 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
149 void lowerIntrinsics(Function &F);
151 void printModule(Module *M);
152 void printModuleTypes(const TypeSymbolTable &ST);
153 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
154 void printFloatingPointConstants(Function &F);
155 void printFunctionSignature(const Function *F, bool Prototype);
157 void printFunction(Function &);
158 void printBasicBlock(BasicBlock *BB);
159 void printLoop(Loop *L);
161 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
162 void printConstant(Constant *CPV);
163 void printConstantWithCast(Constant *CPV, unsigned Opcode);
164 bool printConstExprCast(const ConstantExpr *CE);
165 void printConstantArray(ConstantArray *CPA);
166 void printConstantVector(ConstantVector *CP);
168 // isInlinableInst - Attempt to inline instructions into their uses to build
169 // trees as much as possible. To do this, we have to consistently decide
170 // what is acceptable to inline, so that variable declarations don't get
171 // printed and an extra copy of the expr is not emitted.
173 static bool isInlinableInst(const Instruction &I) {
174 // Always inline cmp instructions, even if they are shared by multiple
175 // expressions. GCC generates horrible code if we don't.
179 // Must be an expression, must be used exactly once. If it is dead, we
180 // emit it inline where it would go.
181 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
182 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
183 isa<LoadInst>(I) || isa<VAArgInst>(I))
184 // Don't inline a load across a store or other bad things!
187 // Must not be used in inline asm
188 if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
190 // Only inline instruction it if it's use is in the same BB as the inst.
191 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
194 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
195 // variables which are accessed with the & operator. This causes GCC to
196 // generate significantly better code than to emit alloca calls directly.
198 static const AllocaInst *isDirectAlloca(const Value *V) {
199 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
200 if (!AI) return false;
201 if (AI->isArrayAllocation())
202 return 0; // FIXME: we can also inline fixed size array allocas!
203 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
208 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
209 static bool isInlineAsm(const Instruction& I) {
210 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
215 // Instruction visitation functions
216 friend class InstVisitor<CWriter>;
218 void visitReturnInst(ReturnInst &I);
219 void visitBranchInst(BranchInst &I);
220 void visitSwitchInst(SwitchInst &I);
221 void visitInvokeInst(InvokeInst &I) {
222 assert(0 && "Lowerinvoke pass didn't work!");
225 void visitUnwindInst(UnwindInst &I) {
226 assert(0 && "Lowerinvoke pass didn't work!");
228 void visitUnreachableInst(UnreachableInst &I);
230 void visitPHINode(PHINode &I);
231 void visitBinaryOperator(Instruction &I);
232 void visitICmpInst(ICmpInst &I);
233 void visitFCmpInst(FCmpInst &I);
235 void visitCastInst (CastInst &I);
236 void visitSelectInst(SelectInst &I);
237 void visitCallInst (CallInst &I);
238 void visitInlineAsm(CallInst &I);
240 void visitMallocInst(MallocInst &I);
241 void visitAllocaInst(AllocaInst &I);
242 void visitFreeInst (FreeInst &I);
243 void visitLoadInst (LoadInst &I);
244 void visitStoreInst (StoreInst &I);
245 void visitGetElementPtrInst(GetElementPtrInst &I);
246 void visitVAArgInst (VAArgInst &I);
248 void visitInstruction(Instruction &I) {
249 cerr << "C Writer does not know about " << I;
253 void outputLValue(Instruction *I) {
254 Out << " " << GetValueName(I) << " = ";
257 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
258 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
259 BasicBlock *Successor, unsigned Indent);
260 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
262 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
263 gep_type_iterator E);
265 std::string GetValueName(const Value *Operand);
269 char CWriter::ID = 0;
271 /// This method inserts names for any unnamed structure types that are used by
272 /// the program, and removes names from structure types that are not used by the
275 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
276 // Get a set of types that are used by the program...
277 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
279 // Loop over the module symbol table, removing types from UT that are
280 // already named, and removing names for types that are not used.
282 TypeSymbolTable &TST = M.getTypeSymbolTable();
283 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
285 TypeSymbolTable::iterator I = TI++;
287 // If this isn't a struct type, remove it from our set of types to name.
288 // This simplifies emission later.
289 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
292 // If this is not used, remove it from the symbol table.
293 std::set<const Type *>::iterator UTI = UT.find(I->second);
297 UT.erase(UTI); // Only keep one name for this type.
301 // UT now contains types that are not named. Loop over it, naming
304 bool Changed = false;
305 unsigned RenameCounter = 0;
306 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
308 if (const StructType *ST = dyn_cast<StructType>(*I)) {
309 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
315 // Loop over all external functions and globals. If we have two with
316 // identical names, merge them.
317 // FIXME: This code should disappear when we don't allow values with the same
318 // names when they have different types!
319 std::map<std::string, GlobalValue*> ExtSymbols;
320 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
322 if (GV->isDeclaration() && GV->hasName()) {
323 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
324 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
326 // Found a conflict, replace this global with the previous one.
327 GlobalValue *OldGV = X.first->second;
328 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
329 GV->eraseFromParent();
334 // Do the same for globals.
335 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
337 GlobalVariable *GV = I++;
338 if (GV->isDeclaration() && GV->hasName()) {
339 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
340 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
342 // Found a conflict, replace this global with the previous one.
343 GlobalValue *OldGV = X.first->second;
344 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
345 GV->eraseFromParent();
354 /// printStructReturnPointerFunctionType - This is like printType for a struct
355 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
356 /// print it as "Struct (*)(...)", for struct return functions.
357 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
358 const ParamAttrsList *PAL,
359 const PointerType *TheTy) {
360 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
361 std::stringstream FunctionInnards;
362 FunctionInnards << " (*) (";
363 bool PrintedType = false;
365 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
366 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
368 for (++I; I != E; ++I) {
370 FunctionInnards << ", ";
371 printType(FunctionInnards, *I,
372 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
375 if (FTy->isVarArg()) {
377 FunctionInnards << ", ...";
378 } else if (!PrintedType) {
379 FunctionInnards << "void";
381 FunctionInnards << ')';
382 std::string tstr = FunctionInnards.str();
383 printType(Out, RetTy,
384 /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
388 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
389 const std::string &NameSoFar) {
390 assert((Ty->isPrimitiveType() || Ty->isInteger()) &&
391 "Invalid type for printSimpleType");
392 switch (Ty->getTypeID()) {
393 case Type::VoidTyID: return Out << "void " << NameSoFar;
394 case Type::IntegerTyID: {
395 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
397 return Out << "bool " << NameSoFar;
398 else if (NumBits <= 8)
399 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
400 else if (NumBits <= 16)
401 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
402 else if (NumBits <= 32)
403 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
405 assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
406 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
409 case Type::FloatTyID: return Out << "float " << NameSoFar;
410 case Type::DoubleTyID: return Out << "double " << NameSoFar;
411 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
412 // present matches host 'long double'.
413 case Type::X86_FP80TyID:
414 case Type::PPC_FP128TyID:
415 case Type::FP128TyID: return Out << "long double " << NameSoFar;
417 cerr << "Unknown primitive type: " << *Ty << "\n";
422 // Pass the Type* and the variable name and this prints out the variable
425 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
426 bool isSigned, const std::string &NameSoFar,
427 bool IgnoreName, const ParamAttrsList* PAL) {
428 if (Ty->isPrimitiveType() || Ty->isInteger()) {
429 printSimpleType(Out, Ty, isSigned, NameSoFar);
433 // Check to see if the type is named.
434 if (!IgnoreName || isa<OpaqueType>(Ty)) {
435 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
436 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
439 switch (Ty->getTypeID()) {
440 case Type::FunctionTyID: {
441 const FunctionType *FTy = cast<FunctionType>(Ty);
442 std::stringstream FunctionInnards;
443 FunctionInnards << " (" << NameSoFar << ") (";
445 for (FunctionType::param_iterator I = FTy->param_begin(),
446 E = FTy->param_end(); I != E; ++I) {
447 if (I != FTy->param_begin())
448 FunctionInnards << ", ";
449 printType(FunctionInnards, *I,
450 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
453 if (FTy->isVarArg()) {
454 if (FTy->getNumParams())
455 FunctionInnards << ", ...";
456 } else if (!FTy->getNumParams()) {
457 FunctionInnards << "void";
459 FunctionInnards << ')';
460 std::string tstr = FunctionInnards.str();
461 printType(Out, FTy->getReturnType(),
462 /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
465 case Type::StructTyID: {
466 const StructType *STy = cast<StructType>(Ty);
467 Out << NameSoFar + " {\n";
469 for (StructType::element_iterator I = STy->element_begin(),
470 E = STy->element_end(); I != E; ++I) {
472 printType(Out, *I, false, "field" + utostr(Idx++));
477 Out << " __attribute__ ((packed))";
481 case Type::PointerTyID: {
482 const PointerType *PTy = cast<PointerType>(Ty);
483 std::string ptrName = "*" + NameSoFar;
485 if (isa<ArrayType>(PTy->getElementType()) ||
486 isa<VectorType>(PTy->getElementType()))
487 ptrName = "(" + ptrName + ")";
489 return printType(Out, PTy->getElementType(), false, ptrName);
492 case Type::ArrayTyID: {
493 const ArrayType *ATy = cast<ArrayType>(Ty);
494 unsigned NumElements = ATy->getNumElements();
495 if (NumElements == 0) NumElements = 1;
496 return printType(Out, ATy->getElementType(), false,
497 NameSoFar + "[" + utostr(NumElements) + "]");
500 case Type::VectorTyID: {
501 const VectorType *PTy = cast<VectorType>(Ty);
502 unsigned NumElements = PTy->getNumElements();
503 if (NumElements == 0) NumElements = 1;
504 return printType(Out, PTy->getElementType(), false,
505 NameSoFar + "[" + utostr(NumElements) + "]");
508 case Type::OpaqueTyID: {
509 static int Count = 0;
510 std::string TyName = "struct opaque_" + itostr(Count++);
511 assert(TypeNames.find(Ty) == TypeNames.end());
512 TypeNames[Ty] = TyName;
513 return Out << TyName << ' ' << NameSoFar;
516 assert(0 && "Unhandled case in getTypeProps!");
523 void CWriter::printConstantArray(ConstantArray *CPA) {
525 // As a special case, print the array as a string if it is an array of
526 // ubytes or an array of sbytes with positive values.
528 const Type *ETy = CPA->getType()->getElementType();
529 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
531 // Make sure the last character is a null char, as automatically added by C
532 if (isString && (CPA->getNumOperands() == 0 ||
533 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
538 // Keep track of whether the last number was a hexadecimal escape
539 bool LastWasHex = false;
541 // Do not include the last character, which we know is null
542 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
543 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
545 // Print it out literally if it is a printable character. The only thing
546 // to be careful about is when the last letter output was a hex escape
547 // code, in which case we have to be careful not to print out hex digits
548 // explicitly (the C compiler thinks it is a continuation of the previous
549 // character, sheesh...)
551 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
553 if (C == '"' || C == '\\')
560 case '\n': Out << "\\n"; break;
561 case '\t': Out << "\\t"; break;
562 case '\r': Out << "\\r"; break;
563 case '\v': Out << "\\v"; break;
564 case '\a': Out << "\\a"; break;
565 case '\"': Out << "\\\""; break;
566 case '\'': Out << "\\\'"; break;
569 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
570 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
579 if (CPA->getNumOperands()) {
581 printConstant(cast<Constant>(CPA->getOperand(0)));
582 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
584 printConstant(cast<Constant>(CPA->getOperand(i)));
591 void CWriter::printConstantVector(ConstantVector *CP) {
593 if (CP->getNumOperands()) {
595 printConstant(cast<Constant>(CP->getOperand(0)));
596 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
598 printConstant(cast<Constant>(CP->getOperand(i)));
604 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
605 // textually as a double (rather than as a reference to a stack-allocated
606 // variable). We decide this by converting CFP to a string and back into a
607 // double, and then checking whether the conversion results in a bit-equal
608 // double to the original value of CFP. This depends on us and the target C
609 // compiler agreeing on the conversion process (which is pretty likely since we
610 // only deal in IEEE FP).
612 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
613 // Do long doubles in hex for now.
614 if (CFP->getType()!=Type::FloatTy && CFP->getType()!=Type::DoubleTy)
616 APFloat APF = APFloat(CFP->getValueAPF()); // copy
617 if (CFP->getType()==Type::FloatTy)
618 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
619 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
621 sprintf(Buffer, "%a", APF.convertToDouble());
622 if (!strncmp(Buffer, "0x", 2) ||
623 !strncmp(Buffer, "-0x", 3) ||
624 !strncmp(Buffer, "+0x", 3))
625 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
628 std::string StrVal = ftostr(APF);
630 while (StrVal[0] == ' ')
631 StrVal.erase(StrVal.begin());
633 // Check to make sure that the stringized number is not some string like "Inf"
634 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
635 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
636 ((StrVal[0] == '-' || StrVal[0] == '+') &&
637 (StrVal[1] >= '0' && StrVal[1] <= '9')))
638 // Reparse stringized version!
639 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
644 /// Print out the casting for a cast operation. This does the double casting
645 /// necessary for conversion to the destination type, if necessary.
646 /// @brief Print a cast
647 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
648 // Print the destination type cast
650 case Instruction::UIToFP:
651 case Instruction::SIToFP:
652 case Instruction::IntToPtr:
653 case Instruction::Trunc:
654 case Instruction::BitCast:
655 case Instruction::FPExt:
656 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
658 printType(Out, DstTy);
661 case Instruction::ZExt:
662 case Instruction::PtrToInt:
663 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
665 printSimpleType(Out, DstTy, false);
668 case Instruction::SExt:
669 case Instruction::FPToSI: // For these, make sure we get a signed dest
671 printSimpleType(Out, DstTy, true);
675 assert(0 && "Invalid cast opcode");
678 // Print the source type cast
680 case Instruction::UIToFP:
681 case Instruction::ZExt:
683 printSimpleType(Out, SrcTy, false);
686 case Instruction::SIToFP:
687 case Instruction::SExt:
689 printSimpleType(Out, SrcTy, true);
692 case Instruction::IntToPtr:
693 case Instruction::PtrToInt:
694 // Avoid "cast to pointer from integer of different size" warnings
695 Out << "(unsigned long)";
697 case Instruction::Trunc:
698 case Instruction::BitCast:
699 case Instruction::FPExt:
700 case Instruction::FPTrunc:
701 case Instruction::FPToSI:
702 case Instruction::FPToUI:
703 break; // These don't need a source cast.
705 assert(0 && "Invalid cast opcode");
710 // printConstant - The LLVM Constant to C Constant converter.
711 void CWriter::printConstant(Constant *CPV) {
712 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
713 switch (CE->getOpcode()) {
714 case Instruction::Trunc:
715 case Instruction::ZExt:
716 case Instruction::SExt:
717 case Instruction::FPTrunc:
718 case Instruction::FPExt:
719 case Instruction::UIToFP:
720 case Instruction::SIToFP:
721 case Instruction::FPToUI:
722 case Instruction::FPToSI:
723 case Instruction::PtrToInt:
724 case Instruction::IntToPtr:
725 case Instruction::BitCast:
727 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
728 if (CE->getOpcode() == Instruction::SExt &&
729 CE->getOperand(0)->getType() == Type::Int1Ty) {
730 // Make sure we really sext from bool here by subtracting from 0
733 printConstant(CE->getOperand(0));
734 if (CE->getType() == Type::Int1Ty &&
735 (CE->getOpcode() == Instruction::Trunc ||
736 CE->getOpcode() == Instruction::FPToUI ||
737 CE->getOpcode() == Instruction::FPToSI ||
738 CE->getOpcode() == Instruction::PtrToInt)) {
739 // Make sure we really truncate to bool here by anding with 1
745 case Instruction::GetElementPtr:
747 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
751 case Instruction::Select:
753 printConstant(CE->getOperand(0));
755 printConstant(CE->getOperand(1));
757 printConstant(CE->getOperand(2));
760 case Instruction::Add:
761 case Instruction::Sub:
762 case Instruction::Mul:
763 case Instruction::SDiv:
764 case Instruction::UDiv:
765 case Instruction::FDiv:
766 case Instruction::URem:
767 case Instruction::SRem:
768 case Instruction::FRem:
769 case Instruction::And:
770 case Instruction::Or:
771 case Instruction::Xor:
772 case Instruction::ICmp:
773 case Instruction::Shl:
774 case Instruction::LShr:
775 case Instruction::AShr:
778 bool NeedsClosingParens = printConstExprCast(CE);
779 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
780 switch (CE->getOpcode()) {
781 case Instruction::Add: Out << " + "; break;
782 case Instruction::Sub: Out << " - "; break;
783 case Instruction::Mul: Out << " * "; break;
784 case Instruction::URem:
785 case Instruction::SRem:
786 case Instruction::FRem: Out << " % "; break;
787 case Instruction::UDiv:
788 case Instruction::SDiv:
789 case Instruction::FDiv: Out << " / "; break;
790 case Instruction::And: Out << " & "; break;
791 case Instruction::Or: Out << " | "; break;
792 case Instruction::Xor: Out << " ^ "; break;
793 case Instruction::Shl: Out << " << "; break;
794 case Instruction::LShr:
795 case Instruction::AShr: Out << " >> "; break;
796 case Instruction::ICmp:
797 switch (CE->getPredicate()) {
798 case ICmpInst::ICMP_EQ: Out << " == "; break;
799 case ICmpInst::ICMP_NE: Out << " != "; break;
800 case ICmpInst::ICMP_SLT:
801 case ICmpInst::ICMP_ULT: Out << " < "; break;
802 case ICmpInst::ICMP_SLE:
803 case ICmpInst::ICMP_ULE: Out << " <= "; break;
804 case ICmpInst::ICMP_SGT:
805 case ICmpInst::ICMP_UGT: Out << " > "; break;
806 case ICmpInst::ICMP_SGE:
807 case ICmpInst::ICMP_UGE: Out << " >= "; break;
808 default: assert(0 && "Illegal ICmp predicate");
811 default: assert(0 && "Illegal opcode here!");
813 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
814 if (NeedsClosingParens)
819 case Instruction::FCmp: {
821 bool NeedsClosingParens = printConstExprCast(CE);
822 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
824 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
828 switch (CE->getPredicate()) {
829 default: assert(0 && "Illegal FCmp predicate");
830 case FCmpInst::FCMP_ORD: op = "ord"; break;
831 case FCmpInst::FCMP_UNO: op = "uno"; break;
832 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
833 case FCmpInst::FCMP_UNE: op = "une"; break;
834 case FCmpInst::FCMP_ULT: op = "ult"; break;
835 case FCmpInst::FCMP_ULE: op = "ule"; break;
836 case FCmpInst::FCMP_UGT: op = "ugt"; break;
837 case FCmpInst::FCMP_UGE: op = "uge"; break;
838 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
839 case FCmpInst::FCMP_ONE: op = "one"; break;
840 case FCmpInst::FCMP_OLT: op = "olt"; break;
841 case FCmpInst::FCMP_OLE: op = "ole"; break;
842 case FCmpInst::FCMP_OGT: op = "ogt"; break;
843 case FCmpInst::FCMP_OGE: op = "oge"; break;
845 Out << "llvm_fcmp_" << op << "(";
846 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
848 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
851 if (NeedsClosingParens)
856 cerr << "CWriter Error: Unhandled constant expression: "
860 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
862 printType(Out, CPV->getType()); // sign doesn't matter
863 Out << ")/*UNDEF*/0)";
867 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
868 const Type* Ty = CI->getType();
869 if (Ty == Type::Int1Ty)
870 Out << (CI->getZExtValue() ? '1' : '0') ;
873 printSimpleType(Out, Ty, false) << ')';
874 if (CI->isMinValue(true))
875 Out << CI->getZExtValue() << 'u';
877 Out << CI->getSExtValue();
878 if (Ty->getPrimitiveSizeInBits() > 32)
885 switch (CPV->getType()->getTypeID()) {
886 case Type::FloatTyID:
887 case Type::DoubleTyID:
888 case Type::X86_FP80TyID:
889 case Type::PPC_FP128TyID:
890 case Type::FP128TyID: {
891 ConstantFP *FPC = cast<ConstantFP>(CPV);
892 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
893 if (I != FPConstantMap.end()) {
894 // Because of FP precision problems we must load from a stack allocated
895 // value that holds the value in hex.
896 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
897 FPC->getType() == Type::DoubleTy ? "double" :
899 << "*)&FPConstant" << I->second << ')';
901 assert(FPC->getType() == Type::FloatTy ||
902 FPC->getType() == Type::DoubleTy);
903 double V = FPC->getType() == Type::FloatTy ?
904 FPC->getValueAPF().convertToFloat() :
905 FPC->getValueAPF().convertToDouble();
909 // FIXME the actual NaN bits should be emitted.
910 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
912 const unsigned long QuietNaN = 0x7ff8UL;
913 //const unsigned long SignalNaN = 0x7ff4UL;
915 // We need to grab the first part of the FP #
918 uint64_t ll = DoubleToBits(V);
919 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
921 std::string Num(&Buffer[0], &Buffer[6]);
922 unsigned long Val = strtoul(Num.c_str(), 0, 16);
924 if (FPC->getType() == Type::FloatTy)
925 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
926 << Buffer << "\") /*nan*/ ";
928 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
929 << Buffer << "\") /*nan*/ ";
930 } else if (IsInf(V)) {
932 if (V < 0) Out << '-';
933 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
937 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
938 // Print out the constant as a floating point number.
940 sprintf(Buffer, "%a", V);
943 Num = ftostr(FPC->getValueAPF());
951 case Type::ArrayTyID:
952 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
953 const ArrayType *AT = cast<ArrayType>(CPV->getType());
955 if (AT->getNumElements()) {
957 Constant *CZ = Constant::getNullValue(AT->getElementType());
959 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
966 printConstantArray(cast<ConstantArray>(CPV));
970 case Type::VectorTyID:
971 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
972 const VectorType *AT = cast<VectorType>(CPV->getType());
974 if (AT->getNumElements()) {
976 Constant *CZ = Constant::getNullValue(AT->getElementType());
978 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
985 printConstantVector(cast<ConstantVector>(CPV));
989 case Type::StructTyID:
990 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
991 const StructType *ST = cast<StructType>(CPV->getType());
993 if (ST->getNumElements()) {
995 printConstant(Constant::getNullValue(ST->getElementType(0)));
996 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
998 printConstant(Constant::getNullValue(ST->getElementType(i)));
1004 if (CPV->getNumOperands()) {
1006 printConstant(cast<Constant>(CPV->getOperand(0)));
1007 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1009 printConstant(cast<Constant>(CPV->getOperand(i)));
1016 case Type::PointerTyID:
1017 if (isa<ConstantPointerNull>(CPV)) {
1019 printType(Out, CPV->getType()); // sign doesn't matter
1020 Out << ")/*NULL*/0)";
1022 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1028 cerr << "Unknown constant type: " << *CPV << "\n";
1033 // Some constant expressions need to be casted back to the original types
1034 // because their operands were casted to the expected type. This function takes
1035 // care of detecting that case and printing the cast for the ConstantExpr.
1036 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
1037 bool NeedsExplicitCast = false;
1038 const Type *Ty = CE->getOperand(0)->getType();
1039 bool TypeIsSigned = false;
1040 switch (CE->getOpcode()) {
1041 case Instruction::LShr:
1042 case Instruction::URem:
1043 case Instruction::UDiv: NeedsExplicitCast = true; break;
1044 case Instruction::AShr:
1045 case Instruction::SRem:
1046 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1047 case Instruction::SExt:
1049 NeedsExplicitCast = true;
1050 TypeIsSigned = true;
1052 case Instruction::ZExt:
1053 case Instruction::Trunc:
1054 case Instruction::FPTrunc:
1055 case Instruction::FPExt:
1056 case Instruction::UIToFP:
1057 case Instruction::SIToFP:
1058 case Instruction::FPToUI:
1059 case Instruction::FPToSI:
1060 case Instruction::PtrToInt:
1061 case Instruction::IntToPtr:
1062 case Instruction::BitCast:
1064 NeedsExplicitCast = true;
1068 if (NeedsExplicitCast) {
1070 if (Ty->isInteger() && Ty != Type::Int1Ty)
1071 printSimpleType(Out, Ty, TypeIsSigned);
1073 printType(Out, Ty); // not integer, sign doesn't matter
1076 return NeedsExplicitCast;
1079 // Print a constant assuming that it is the operand for a given Opcode. The
1080 // opcodes that care about sign need to cast their operands to the expected
1081 // type before the operation proceeds. This function does the casting.
1082 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1084 // Extract the operand's type, we'll need it.
1085 const Type* OpTy = CPV->getType();
1087 // Indicate whether to do the cast or not.
1088 bool shouldCast = false;
1089 bool typeIsSigned = false;
1091 // Based on the Opcode for which this Constant is being written, determine
1092 // the new type to which the operand should be casted by setting the value
1093 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1097 // for most instructions, it doesn't matter
1099 case Instruction::LShr:
1100 case Instruction::UDiv:
1101 case Instruction::URem:
1104 case Instruction::AShr:
1105 case Instruction::SDiv:
1106 case Instruction::SRem:
1108 typeIsSigned = true;
1112 // Write out the casted constant if we should, otherwise just write the
1116 printSimpleType(Out, OpTy, typeIsSigned);
1124 std::string CWriter::GetValueName(const Value *Operand) {
1127 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1128 std::string VarName;
1130 Name = Operand->getName();
1131 VarName.reserve(Name.capacity());
1133 for (std::string::iterator I = Name.begin(), E = Name.end();
1137 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1138 (ch >= '0' && ch <= '9') || ch == '_'))
1144 Name = "llvm_cbe_" + VarName;
1146 Name = Mang->getValueName(Operand);
1152 void CWriter::writeOperandInternal(Value *Operand) {
1153 if (Instruction *I = dyn_cast<Instruction>(Operand))
1154 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1155 // Should we inline this instruction to build a tree?
1162 Constant* CPV = dyn_cast<Constant>(Operand);
1164 if (CPV && !isa<GlobalValue>(CPV))
1167 Out << GetValueName(Operand);
1170 void CWriter::writeOperandRaw(Value *Operand) {
1171 Constant* CPV = dyn_cast<Constant>(Operand);
1172 if (CPV && !isa<GlobalValue>(CPV)) {
1175 Out << GetValueName(Operand);
1179 void CWriter::writeOperand(Value *Operand) {
1180 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1181 Out << "(&"; // Global variables are referenced as their addresses by llvm
1183 writeOperandInternal(Operand);
1185 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1189 // Some instructions need to have their result value casted back to the
1190 // original types because their operands were casted to the expected type.
1191 // This function takes care of detecting that case and printing the cast
1192 // for the Instruction.
1193 bool CWriter::writeInstructionCast(const Instruction &I) {
1194 const Type *Ty = I.getOperand(0)->getType();
1195 switch (I.getOpcode()) {
1196 case Instruction::LShr:
1197 case Instruction::URem:
1198 case Instruction::UDiv:
1200 printSimpleType(Out, Ty, false);
1203 case Instruction::AShr:
1204 case Instruction::SRem:
1205 case Instruction::SDiv:
1207 printSimpleType(Out, Ty, true);
1215 // Write the operand with a cast to another type based on the Opcode being used.
1216 // This will be used in cases where an instruction has specific type
1217 // requirements (usually signedness) for its operands.
1218 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1220 // Extract the operand's type, we'll need it.
1221 const Type* OpTy = Operand->getType();
1223 // Indicate whether to do the cast or not.
1224 bool shouldCast = false;
1226 // Indicate whether the cast should be to a signed type or not.
1227 bool castIsSigned = false;
1229 // Based on the Opcode for which this Operand is being written, determine
1230 // the new type to which the operand should be casted by setting the value
1231 // of OpTy. If we change OpTy, also set shouldCast to true.
1234 // for most instructions, it doesn't matter
1236 case Instruction::LShr:
1237 case Instruction::UDiv:
1238 case Instruction::URem: // Cast to unsigned first
1240 castIsSigned = false;
1242 case Instruction::GetElementPtr:
1243 case Instruction::AShr:
1244 case Instruction::SDiv:
1245 case Instruction::SRem: // Cast to signed first
1247 castIsSigned = true;
1251 // Write out the casted operand if we should, otherwise just write the
1255 printSimpleType(Out, OpTy, castIsSigned);
1257 writeOperand(Operand);
1260 writeOperand(Operand);
1263 // Write the operand with a cast to another type based on the icmp predicate
1265 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1266 // This has to do a cast to ensure the operand has the right signedness.
1267 // Also, if the operand is a pointer, we make sure to cast to an integer when
1268 // doing the comparison both for signedness and so that the C compiler doesn't
1269 // optimize things like "p < NULL" to false (p may contain an integer value
1271 bool shouldCast = Cmp.isRelational();
1273 // Write out the casted operand if we should, otherwise just write the
1276 writeOperand(Operand);
1280 // Should this be a signed comparison? If so, convert to signed.
1281 bool castIsSigned = Cmp.isSignedPredicate();
1283 // If the operand was a pointer, convert to a large integer type.
1284 const Type* OpTy = Operand->getType();
1285 if (isa<PointerType>(OpTy))
1286 OpTy = TD->getIntPtrType();
1289 printSimpleType(Out, OpTy, castIsSigned);
1291 writeOperand(Operand);
1295 // generateCompilerSpecificCode - This is where we add conditional compilation
1296 // directives to cater to specific compilers as need be.
1298 static void generateCompilerSpecificCode(std::ostream& Out) {
1299 // Alloca is hard to get, and we don't want to include stdlib.h here.
1300 Out << "/* get a declaration for alloca */\n"
1301 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1302 << "#define alloca(x) __builtin_alloca((x))\n"
1303 << "#define _alloca(x) __builtin_alloca((x))\n"
1304 << "#elif defined(__APPLE__)\n"
1305 << "extern void *__builtin_alloca(unsigned long);\n"
1306 << "#define alloca(x) __builtin_alloca(x)\n"
1307 << "#define longjmp _longjmp\n"
1308 << "#define setjmp _setjmp\n"
1309 << "#elif defined(__sun__)\n"
1310 << "#if defined(__sparcv9)\n"
1311 << "extern void *__builtin_alloca(unsigned long);\n"
1313 << "extern void *__builtin_alloca(unsigned int);\n"
1315 << "#define alloca(x) __builtin_alloca(x)\n"
1316 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1317 << "#define alloca(x) __builtin_alloca(x)\n"
1318 << "#elif defined(_MSC_VER)\n"
1319 << "#define inline _inline\n"
1320 << "#define alloca(x) _alloca(x)\n"
1322 << "#include <alloca.h>\n"
1325 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1326 // If we aren't being compiled with GCC, just drop these attributes.
1327 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1328 << "#define __attribute__(X)\n"
1331 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1332 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1333 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1334 << "#elif defined(__GNUC__)\n"
1335 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1337 << "#define __EXTERNAL_WEAK__\n"
1340 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1341 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1342 << "#define __ATTRIBUTE_WEAK__\n"
1343 << "#elif defined(__GNUC__)\n"
1344 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1346 << "#define __ATTRIBUTE_WEAK__\n"
1349 // Add hidden visibility support. FIXME: APPLE_CC?
1350 Out << "#if defined(__GNUC__)\n"
1351 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1354 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1355 // From the GCC documentation:
1357 // double __builtin_nan (const char *str)
1359 // This is an implementation of the ISO C99 function nan.
1361 // Since ISO C99 defines this function in terms of strtod, which we do
1362 // not implement, a description of the parsing is in order. The string is
1363 // parsed as by strtol; that is, the base is recognized by leading 0 or
1364 // 0x prefixes. The number parsed is placed in the significand such that
1365 // the least significant bit of the number is at the least significant
1366 // bit of the significand. The number is truncated to fit the significand
1367 // field provided. The significand is forced to be a quiet NaN.
1369 // This function, if given a string literal, is evaluated early enough
1370 // that it is considered a compile-time constant.
1372 // float __builtin_nanf (const char *str)
1374 // Similar to __builtin_nan, except the return type is float.
1376 // double __builtin_inf (void)
1378 // Similar to __builtin_huge_val, except a warning is generated if the
1379 // target floating-point format does not support infinities. This
1380 // function is suitable for implementing the ISO C99 macro INFINITY.
1382 // float __builtin_inff (void)
1384 // Similar to __builtin_inf, except the return type is float.
1385 Out << "#ifdef __GNUC__\n"
1386 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1387 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1388 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1389 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1390 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1391 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1392 << "#define LLVM_PREFETCH(addr,rw,locality) "
1393 "__builtin_prefetch(addr,rw,locality)\n"
1394 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1395 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1396 << "#define LLVM_ASM __asm__\n"
1398 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1399 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1400 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1401 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1402 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1403 << "#define LLVM_INFF 0.0F /* Float */\n"
1404 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1405 << "#define __ATTRIBUTE_CTOR__\n"
1406 << "#define __ATTRIBUTE_DTOR__\n"
1407 << "#define LLVM_ASM(X)\n"
1410 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1411 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1412 << "#define __builtin_stack_restore(X) /* noop */\n"
1415 // Output target-specific code that should be inserted into main.
1416 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1419 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1420 /// the StaticTors set.
1421 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1422 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1423 if (!InitList) return;
1425 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1426 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1427 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1429 if (CS->getOperand(1)->isNullValue())
1430 return; // Found a null terminator, exit printing.
1431 Constant *FP = CS->getOperand(1);
1432 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1434 FP = CE->getOperand(0);
1435 if (Function *F = dyn_cast<Function>(FP))
1436 StaticTors.insert(F);
1440 enum SpecialGlobalClass {
1442 GlobalCtors, GlobalDtors,
1446 /// getGlobalVariableClass - If this is a global that is specially recognized
1447 /// by LLVM, return a code that indicates how we should handle it.
1448 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1449 // If this is a global ctors/dtors list, handle it now.
1450 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1451 if (GV->getName() == "llvm.global_ctors")
1453 else if (GV->getName() == "llvm.global_dtors")
1457 // Otherwise, it it is other metadata, don't print it. This catches things
1458 // like debug information.
1459 if (GV->getSection() == "llvm.metadata")
1466 bool CWriter::doInitialization(Module &M) {
1470 TD = new TargetData(&M);
1471 IL = new IntrinsicLowering(*TD);
1472 IL->AddPrototypes(M);
1474 // Ensure that all structure types have names...
1475 Mang = new Mangler(M);
1476 Mang->markCharUnacceptable('.');
1478 // Keep track of which functions are static ctors/dtors so they can have
1479 // an attribute added to their prototypes.
1480 std::set<Function*> StaticCtors, StaticDtors;
1481 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1483 switch (getGlobalVariableClass(I)) {
1486 FindStaticTors(I, StaticCtors);
1489 FindStaticTors(I, StaticDtors);
1494 // get declaration for alloca
1495 Out << "/* Provide Declarations */\n";
1496 Out << "#include <stdarg.h>\n"; // Varargs support
1497 Out << "#include <setjmp.h>\n"; // Unwind support
1498 generateCompilerSpecificCode(Out);
1500 // Provide a definition for `bool' if not compiling with a C++ compiler.
1502 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1504 << "\n\n/* Support for floating point constants */\n"
1505 << "typedef unsigned long long ConstantDoubleTy;\n"
1506 << "typedef unsigned int ConstantFloatTy;\n"
1507 << "typedef struct { unsigned long long f1; unsigned short f2; "
1508 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1509 // This is used for both kinds of 128-bit long double; meaning differs.
1510 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1511 " ConstantFP128Ty;\n"
1512 << "\n\n/* Global Declarations */\n";
1514 // First output all the declarations for the program, because C requires
1515 // Functions & globals to be declared before they are used.
1518 // Loop over the symbol table, emitting all named constants...
1519 printModuleTypes(M.getTypeSymbolTable());
1521 // Global variable declarations...
1522 if (!M.global_empty()) {
1523 Out << "\n/* External Global Variable Declarations */\n";
1524 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1527 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
1529 else if (I->hasDLLImportLinkage())
1530 Out << "__declspec(dllimport) ";
1532 continue; // Internal Global
1534 // Thread Local Storage
1535 if (I->isThreadLocal())
1538 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1540 if (I->hasExternalWeakLinkage())
1541 Out << " __EXTERNAL_WEAK__";
1546 // Function declarations
1547 Out << "\n/* Function Declarations */\n";
1548 Out << "double fmod(double, double);\n"; // Support for FP rem
1549 Out << "float fmodf(float, float);\n";
1550 Out << "long double fmodl(long double, long double);\n";
1552 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1553 // Don't print declarations for intrinsic functions.
1554 if (!I->getIntrinsicID() && I->getName() != "setjmp" &&
1555 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1556 if (I->hasExternalWeakLinkage())
1558 printFunctionSignature(I, true);
1559 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1560 Out << " __ATTRIBUTE_WEAK__";
1561 if (I->hasExternalWeakLinkage())
1562 Out << " __EXTERNAL_WEAK__";
1563 if (StaticCtors.count(I))
1564 Out << " __ATTRIBUTE_CTOR__";
1565 if (StaticDtors.count(I))
1566 Out << " __ATTRIBUTE_DTOR__";
1567 if (I->hasHiddenVisibility())
1568 Out << " __HIDDEN__";
1570 if (I->hasName() && I->getName()[0] == 1)
1571 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1577 // Output the global variable declarations
1578 if (!M.global_empty()) {
1579 Out << "\n\n/* Global Variable Declarations */\n";
1580 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1582 if (!I->isDeclaration()) {
1583 // Ignore special globals, such as debug info.
1584 if (getGlobalVariableClass(I))
1587 if (I->hasInternalLinkage())
1592 // Thread Local Storage
1593 if (I->isThreadLocal())
1596 printType(Out, I->getType()->getElementType(), false,
1599 if (I->hasLinkOnceLinkage())
1600 Out << " __attribute__((common))";
1601 else if (I->hasWeakLinkage())
1602 Out << " __ATTRIBUTE_WEAK__";
1603 else if (I->hasExternalWeakLinkage())
1604 Out << " __EXTERNAL_WEAK__";
1605 if (I->hasHiddenVisibility())
1606 Out << " __HIDDEN__";
1611 // Output the global variable definitions and contents...
1612 if (!M.global_empty()) {
1613 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1614 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1616 if (!I->isDeclaration()) {
1617 // Ignore special globals, such as debug info.
1618 if (getGlobalVariableClass(I))
1621 if (I->hasInternalLinkage())
1623 else if (I->hasDLLImportLinkage())
1624 Out << "__declspec(dllimport) ";
1625 else if (I->hasDLLExportLinkage())
1626 Out << "__declspec(dllexport) ";
1628 // Thread Local Storage
1629 if (I->isThreadLocal())
1632 printType(Out, I->getType()->getElementType(), false,
1634 if (I->hasLinkOnceLinkage())
1635 Out << " __attribute__((common))";
1636 else if (I->hasWeakLinkage())
1637 Out << " __ATTRIBUTE_WEAK__";
1639 if (I->hasHiddenVisibility())
1640 Out << " __HIDDEN__";
1642 // If the initializer is not null, emit the initializer. If it is null,
1643 // we try to avoid emitting large amounts of zeros. The problem with
1644 // this, however, occurs when the variable has weak linkage. In this
1645 // case, the assembler will complain about the variable being both weak
1646 // and common, so we disable this optimization.
1647 if (!I->getInitializer()->isNullValue()) {
1649 writeOperand(I->getInitializer());
1650 } else if (I->hasWeakLinkage()) {
1651 // We have to specify an initializer, but it doesn't have to be
1652 // complete. If the value is an aggregate, print out { 0 }, and let
1653 // the compiler figure out the rest of the zeros.
1655 if (isa<StructType>(I->getInitializer()->getType()) ||
1656 isa<ArrayType>(I->getInitializer()->getType()) ||
1657 isa<VectorType>(I->getInitializer()->getType())) {
1660 // Just print it out normally.
1661 writeOperand(I->getInitializer());
1669 Out << "\n\n/* Function Bodies */\n";
1671 // Emit some helper functions for dealing with FCMP instruction's
1673 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1674 Out << "return X == X && Y == Y; }\n";
1675 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1676 Out << "return X != X || Y != Y; }\n";
1677 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1678 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1679 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1680 Out << "return X != Y; }\n";
1681 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1682 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1683 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1684 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1685 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1686 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1687 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1688 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1689 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1690 Out << "return X == Y ; }\n";
1691 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1692 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1693 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1694 Out << "return X < Y ; }\n";
1695 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1696 Out << "return X > Y ; }\n";
1697 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1698 Out << "return X <= Y ; }\n";
1699 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1700 Out << "return X >= Y ; }\n";
1705 /// Output all floating point constants that cannot be printed accurately...
1706 void CWriter::printFloatingPointConstants(Function &F) {
1707 // Scan the module for floating point constants. If any FP constant is used
1708 // in the function, we want to redirect it here so that we do not depend on
1709 // the precision of the printed form, unless the printed form preserves
1712 static unsigned FPCounter = 0;
1713 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1715 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1716 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1717 !FPConstantMap.count(FPC)) {
1718 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1720 if (FPC->getType() == Type::DoubleTy) {
1721 double Val = FPC->getValueAPF().convertToDouble();
1722 uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
1723 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1724 << " = 0x" << std::hex << i << std::dec
1725 << "ULL; /* " << Val << " */\n";
1726 } else if (FPC->getType() == Type::FloatTy) {
1727 float Val = FPC->getValueAPF().convertToFloat();
1728 uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
1730 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1731 << " = 0x" << std::hex << i << std::dec
1732 << "U; /* " << Val << " */\n";
1733 } else if (FPC->getType() == Type::X86_FP80Ty) {
1734 // api needed to prevent premature destruction
1735 APInt api = FPC->getValueAPF().convertToAPInt();
1736 const uint64_t *p = api.getRawData();
1737 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
1738 << " = { 0x" << std::hex
1739 << ((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16)
1740 << ", 0x" << (uint16_t)(p[0] >> 48) << ",0,0,0"
1741 << "}; /* Long double constant */\n" << std::dec;
1742 } else if (FPC->getType() == Type::PPC_FP128Ty) {
1743 APInt api = FPC->getValueAPF().convertToAPInt();
1744 const uint64_t *p = api.getRawData();
1745 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
1746 << " = { 0x" << std::hex
1747 << p[0] << ", 0x" << p[1]
1748 << "}; /* Long double constant */\n" << std::dec;
1751 assert(0 && "Unknown float type!");
1758 /// printSymbolTable - Run through symbol table looking for type names. If a
1759 /// type name is found, emit its declaration...
1761 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1762 Out << "/* Helper union for bitcasts */\n";
1763 Out << "typedef union {\n";
1764 Out << " unsigned int Int32;\n";
1765 Out << " unsigned long long Int64;\n";
1766 Out << " float Float;\n";
1767 Out << " double Double;\n";
1768 Out << "} llvmBitCastUnion;\n";
1770 // We are only interested in the type plane of the symbol table.
1771 TypeSymbolTable::const_iterator I = TST.begin();
1772 TypeSymbolTable::const_iterator End = TST.end();
1774 // If there are no type names, exit early.
1775 if (I == End) return;
1777 // Print out forward declarations for structure types before anything else!
1778 Out << "/* Structure forward decls */\n";
1779 for (; I != End; ++I) {
1780 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1781 Out << Name << ";\n";
1782 TypeNames.insert(std::make_pair(I->second, Name));
1787 // Now we can print out typedefs. Above, we guaranteed that this can only be
1788 // for struct or opaque types.
1789 Out << "/* Typedefs */\n";
1790 for (I = TST.begin(); I != End; ++I) {
1791 std::string Name = "l_" + Mang->makeNameProper(I->first);
1793 printType(Out, I->second, false, Name);
1799 // Keep track of which structures have been printed so far...
1800 std::set<const StructType *> StructPrinted;
1802 // Loop over all structures then push them into the stack so they are
1803 // printed in the correct order.
1805 Out << "/* Structure contents */\n";
1806 for (I = TST.begin(); I != End; ++I)
1807 if (const StructType *STy = dyn_cast<StructType>(I->second))
1808 // Only print out used types!
1809 printContainedStructs(STy, StructPrinted);
1812 // Push the struct onto the stack and recursively push all structs
1813 // this one depends on.
1815 // TODO: Make this work properly with vector types
1817 void CWriter::printContainedStructs(const Type *Ty,
1818 std::set<const StructType*> &StructPrinted){
1819 // Don't walk through pointers.
1820 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1822 // Print all contained types first.
1823 for (Type::subtype_iterator I = Ty->subtype_begin(),
1824 E = Ty->subtype_end(); I != E; ++I)
1825 printContainedStructs(*I, StructPrinted);
1827 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1828 // Check to see if we have already printed this struct.
1829 if (StructPrinted.insert(STy).second) {
1830 // Print structure type out.
1831 std::string Name = TypeNames[STy];
1832 printType(Out, STy, false, Name, true);
1838 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1839 /// isStructReturn - Should this function actually return a struct by-value?
1840 bool isStructReturn = F->isStructReturn();
1842 if (F->hasInternalLinkage()) Out << "static ";
1843 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1844 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1845 switch (F->getCallingConv()) {
1846 case CallingConv::X86_StdCall:
1847 Out << "__stdcall ";
1849 case CallingConv::X86_FastCall:
1850 Out << "__fastcall ";
1854 // Loop over the arguments, printing them...
1855 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1856 const ParamAttrsList *PAL = F->getParamAttrs();
1858 std::stringstream FunctionInnards;
1860 // Print out the name...
1861 FunctionInnards << GetValueName(F) << '(';
1863 bool PrintedArg = false;
1864 if (!F->isDeclaration()) {
1865 if (!F->arg_empty()) {
1866 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1868 // If this is a struct-return function, don't print the hidden
1869 // struct-return argument.
1870 if (isStructReturn) {
1871 assert(I != E && "Invalid struct return function!");
1875 std::string ArgName;
1877 for (; I != E; ++I) {
1878 if (PrintedArg) FunctionInnards << ", ";
1879 if (I->hasName() || !Prototype)
1880 ArgName = GetValueName(I);
1883 printType(FunctionInnards, I->getType(),
1884 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt),
1891 // Loop over the arguments, printing them.
1892 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1894 // If this is a struct-return function, don't print the hidden
1895 // struct-return argument.
1896 if (isStructReturn) {
1897 assert(I != E && "Invalid struct return function!");
1902 for (; I != E; ++I) {
1903 if (PrintedArg) FunctionInnards << ", ";
1904 printType(FunctionInnards, *I,
1905 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
1911 // Finish printing arguments... if this is a vararg function, print the ...,
1912 // unless there are no known types, in which case, we just emit ().
1914 if (FT->isVarArg() && PrintedArg) {
1915 if (PrintedArg) FunctionInnards << ", ";
1916 FunctionInnards << "..."; // Output varargs portion of signature!
1917 } else if (!FT->isVarArg() && !PrintedArg) {
1918 FunctionInnards << "void"; // ret() -> ret(void) in C.
1920 FunctionInnards << ')';
1922 // Get the return tpe for the function.
1924 if (!isStructReturn)
1925 RetTy = F->getReturnType();
1927 // If this is a struct-return function, print the struct-return type.
1928 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1931 // Print out the return type and the signature built above.
1932 printType(Out, RetTy,
1933 /*isSigned=*/ PAL && PAL->paramHasAttr(0, ParamAttr::SExt),
1934 FunctionInnards.str());
1937 static inline bool isFPIntBitCast(const Instruction &I) {
1938 if (!isa<BitCastInst>(I))
1940 const Type *SrcTy = I.getOperand(0)->getType();
1941 const Type *DstTy = I.getType();
1942 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1943 (DstTy->isFloatingPoint() && SrcTy->isInteger());
1946 void CWriter::printFunction(Function &F) {
1947 /// isStructReturn - Should this function actually return a struct by-value?
1948 bool isStructReturn = F.isStructReturn();
1950 printFunctionSignature(&F, false);
1953 // If this is a struct return function, handle the result with magic.
1954 if (isStructReturn) {
1955 const Type *StructTy =
1956 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1958 printType(Out, StructTy, false, "StructReturn");
1959 Out << "; /* Struct return temporary */\n";
1962 printType(Out, F.arg_begin()->getType(), false,
1963 GetValueName(F.arg_begin()));
1964 Out << " = &StructReturn;\n";
1967 bool PrintedVar = false;
1969 // print local variable information for the function
1970 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
1971 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1973 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
1974 Out << "; /* Address-exposed local */\n";
1976 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1978 printType(Out, I->getType(), false, GetValueName(&*I));
1981 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1983 printType(Out, I->getType(), false,
1984 GetValueName(&*I)+"__PHI_TEMPORARY");
1989 // We need a temporary for the BitCast to use so it can pluck a value out
1990 // of a union to do the BitCast. This is separate from the need for a
1991 // variable to hold the result of the BitCast.
1992 if (isFPIntBitCast(*I)) {
1993 Out << " llvmBitCastUnion " << GetValueName(&*I)
1994 << "__BITCAST_TEMPORARY;\n";
2002 if (F.hasExternalLinkage() && F.getName() == "main")
2003 Out << " CODE_FOR_MAIN();\n";
2005 // print the basic blocks
2006 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2007 if (Loop *L = LI->getLoopFor(BB)) {
2008 if (L->getHeader() == BB && L->getParentLoop() == 0)
2011 printBasicBlock(BB);
2018 void CWriter::printLoop(Loop *L) {
2019 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2020 << "' to make GCC happy */\n";
2021 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2022 BasicBlock *BB = L->getBlocks()[i];
2023 Loop *BBLoop = LI->getLoopFor(BB);
2025 printBasicBlock(BB);
2026 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2029 Out << " } while (1); /* end of syntactic loop '"
2030 << L->getHeader()->getName() << "' */\n";
2033 void CWriter::printBasicBlock(BasicBlock *BB) {
2035 // Don't print the label for the basic block if there are no uses, or if
2036 // the only terminator use is the predecessor basic block's terminator.
2037 // We have to scan the use list because PHI nodes use basic blocks too but
2038 // do not require a label to be generated.
2040 bool NeedsLabel = false;
2041 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2042 if (isGotoCodeNecessary(*PI, BB)) {
2047 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2049 // Output all of the instructions in the basic block...
2050 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2052 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2053 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2062 // Don't emit prefix or suffix for the terminator...
2063 visit(*BB->getTerminator());
2067 // Specific Instruction type classes... note that all of the casts are
2068 // necessary because we use the instruction classes as opaque types...
2070 void CWriter::visitReturnInst(ReturnInst &I) {
2071 // If this is a struct return function, return the temporary struct.
2072 bool isStructReturn = I.getParent()->getParent()->isStructReturn();
2074 if (isStructReturn) {
2075 Out << " return StructReturn;\n";
2079 // Don't output a void return if this is the last basic block in the function
2080 if (I.getNumOperands() == 0 &&
2081 &*--I.getParent()->getParent()->end() == I.getParent() &&
2082 !I.getParent()->size() == 1) {
2087 if (I.getNumOperands()) {
2089 writeOperand(I.getOperand(0));
2094 void CWriter::visitSwitchInst(SwitchInst &SI) {
2097 writeOperand(SI.getOperand(0));
2098 Out << ") {\n default:\n";
2099 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2100 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2102 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2104 writeOperand(SI.getOperand(i));
2106 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2107 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2108 printBranchToBlock(SI.getParent(), Succ, 2);
2109 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2115 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2116 Out << " /*UNREACHABLE*/;\n";
2119 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2120 /// FIXME: This should be reenabled, but loop reordering safe!!
2123 if (next(Function::iterator(From)) != Function::iterator(To))
2124 return true; // Not the direct successor, we need a goto.
2126 //isa<SwitchInst>(From->getTerminator())
2128 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2133 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2134 BasicBlock *Successor,
2136 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2137 PHINode *PN = cast<PHINode>(I);
2138 // Now we have to do the printing.
2139 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2140 if (!isa<UndefValue>(IV)) {
2141 Out << std::string(Indent, ' ');
2142 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2144 Out << "; /* for PHI node */\n";
2149 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2151 if (isGotoCodeNecessary(CurBB, Succ)) {
2152 Out << std::string(Indent, ' ') << " goto ";
2158 // Branch instruction printing - Avoid printing out a branch to a basic block
2159 // that immediately succeeds the current one.
2161 void CWriter::visitBranchInst(BranchInst &I) {
2163 if (I.isConditional()) {
2164 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2166 writeOperand(I.getCondition());
2169 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2170 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2172 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2173 Out << " } else {\n";
2174 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2175 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2178 // First goto not necessary, assume second one is...
2180 writeOperand(I.getCondition());
2183 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2184 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2189 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2190 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2195 // PHI nodes get copied into temporary values at the end of predecessor basic
2196 // blocks. We now need to copy these temporary values into the REAL value for
2198 void CWriter::visitPHINode(PHINode &I) {
2200 Out << "__PHI_TEMPORARY";
2204 void CWriter::visitBinaryOperator(Instruction &I) {
2205 // binary instructions, shift instructions, setCond instructions.
2206 assert(!isa<PointerType>(I.getType()));
2208 // We must cast the results of binary operations which might be promoted.
2209 bool needsCast = false;
2210 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2211 || (I.getType() == Type::FloatTy)) {
2214 printType(Out, I.getType(), false);
2218 // If this is a negation operation, print it out as such. For FP, we don't
2219 // want to print "-0.0 - X".
2220 if (BinaryOperator::isNeg(&I)) {
2222 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2224 } else if (I.getOpcode() == Instruction::FRem) {
2225 // Output a call to fmod/fmodf instead of emitting a%b
2226 if (I.getType() == Type::FloatTy)
2228 else if (I.getType() == Type::DoubleTy)
2230 else // all 3 flavors of long double
2232 writeOperand(I.getOperand(0));
2234 writeOperand(I.getOperand(1));
2238 // Write out the cast of the instruction's value back to the proper type
2240 bool NeedsClosingParens = writeInstructionCast(I);
2242 // Certain instructions require the operand to be forced to a specific type
2243 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2244 // below for operand 1
2245 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2247 switch (I.getOpcode()) {
2248 case Instruction::Add: Out << " + "; break;
2249 case Instruction::Sub: Out << " - "; break;
2250 case Instruction::Mul: Out << " * "; break;
2251 case Instruction::URem:
2252 case Instruction::SRem:
2253 case Instruction::FRem: Out << " % "; break;
2254 case Instruction::UDiv:
2255 case Instruction::SDiv:
2256 case Instruction::FDiv: Out << " / "; break;
2257 case Instruction::And: Out << " & "; break;
2258 case Instruction::Or: Out << " | "; break;
2259 case Instruction::Xor: Out << " ^ "; break;
2260 case Instruction::Shl : Out << " << "; break;
2261 case Instruction::LShr:
2262 case Instruction::AShr: Out << " >> "; break;
2263 default: cerr << "Invalid operator type!" << I; abort();
2266 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2267 if (NeedsClosingParens)
2276 void CWriter::visitICmpInst(ICmpInst &I) {
2277 // We must cast the results of icmp which might be promoted.
2278 bool needsCast = false;
2280 // Write out the cast of the instruction's value back to the proper type
2282 bool NeedsClosingParens = writeInstructionCast(I);
2284 // Certain icmp predicate require the operand to be forced to a specific type
2285 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2286 // below for operand 1
2287 writeOperandWithCast(I.getOperand(0), I);
2289 switch (I.getPredicate()) {
2290 case ICmpInst::ICMP_EQ: Out << " == "; break;
2291 case ICmpInst::ICMP_NE: Out << " != "; break;
2292 case ICmpInst::ICMP_ULE:
2293 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2294 case ICmpInst::ICMP_UGE:
2295 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2296 case ICmpInst::ICMP_ULT:
2297 case ICmpInst::ICMP_SLT: Out << " < "; break;
2298 case ICmpInst::ICMP_UGT:
2299 case ICmpInst::ICMP_SGT: Out << " > "; break;
2300 default: cerr << "Invalid icmp predicate!" << I; abort();
2303 writeOperandWithCast(I.getOperand(1), I);
2304 if (NeedsClosingParens)
2312 void CWriter::visitFCmpInst(FCmpInst &I) {
2313 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2317 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2323 switch (I.getPredicate()) {
2324 default: assert(0 && "Illegal FCmp predicate");
2325 case FCmpInst::FCMP_ORD: op = "ord"; break;
2326 case FCmpInst::FCMP_UNO: op = "uno"; break;
2327 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2328 case FCmpInst::FCMP_UNE: op = "une"; break;
2329 case FCmpInst::FCMP_ULT: op = "ult"; break;
2330 case FCmpInst::FCMP_ULE: op = "ule"; break;
2331 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2332 case FCmpInst::FCMP_UGE: op = "uge"; break;
2333 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2334 case FCmpInst::FCMP_ONE: op = "one"; break;
2335 case FCmpInst::FCMP_OLT: op = "olt"; break;
2336 case FCmpInst::FCMP_OLE: op = "ole"; break;
2337 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2338 case FCmpInst::FCMP_OGE: op = "oge"; break;
2341 Out << "llvm_fcmp_" << op << "(";
2342 // Write the first operand
2343 writeOperand(I.getOperand(0));
2345 // Write the second operand
2346 writeOperand(I.getOperand(1));
2350 static const char * getFloatBitCastField(const Type *Ty) {
2351 switch (Ty->getTypeID()) {
2352 default: assert(0 && "Invalid Type");
2353 case Type::FloatTyID: return "Float";
2354 case Type::DoubleTyID: return "Double";
2355 case Type::IntegerTyID: {
2356 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2365 void CWriter::visitCastInst(CastInst &I) {
2366 const Type *DstTy = I.getType();
2367 const Type *SrcTy = I.getOperand(0)->getType();
2369 if (isFPIntBitCast(I)) {
2370 // These int<->float and long<->double casts need to be handled specially
2371 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2372 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2373 writeOperand(I.getOperand(0));
2374 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2375 << getFloatBitCastField(I.getType());
2377 printCast(I.getOpcode(), SrcTy, DstTy);
2378 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
2379 // Make sure we really get a sext from bool by subtracing the bool from 0
2382 writeOperand(I.getOperand(0));
2383 if (DstTy == Type::Int1Ty &&
2384 (I.getOpcode() == Instruction::Trunc ||
2385 I.getOpcode() == Instruction::FPToUI ||
2386 I.getOpcode() == Instruction::FPToSI ||
2387 I.getOpcode() == Instruction::PtrToInt)) {
2388 // Make sure we really get a trunc to bool by anding the operand with 1
2395 void CWriter::visitSelectInst(SelectInst &I) {
2397 writeOperand(I.getCondition());
2399 writeOperand(I.getTrueValue());
2401 writeOperand(I.getFalseValue());
2406 void CWriter::lowerIntrinsics(Function &F) {
2407 // This is used to keep track of intrinsics that get generated to a lowered
2408 // function. We must generate the prototypes before the function body which
2409 // will only be expanded on first use (by the loop below).
2410 std::vector<Function*> prototypesToGen;
2412 // Examine all the instructions in this function to find the intrinsics that
2413 // need to be lowered.
2414 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2415 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2416 if (CallInst *CI = dyn_cast<CallInst>(I++))
2417 if (Function *F = CI->getCalledFunction())
2418 switch (F->getIntrinsicID()) {
2419 case Intrinsic::not_intrinsic:
2420 case Intrinsic::vastart:
2421 case Intrinsic::vacopy:
2422 case Intrinsic::vaend:
2423 case Intrinsic::returnaddress:
2424 case Intrinsic::frameaddress:
2425 case Intrinsic::setjmp:
2426 case Intrinsic::longjmp:
2427 case Intrinsic::prefetch:
2428 case Intrinsic::dbg_stoppoint:
2429 case Intrinsic::powi:
2430 // We directly implement these intrinsics
2433 // If this is an intrinsic that directly corresponds to a GCC
2434 // builtin, we handle it.
2435 const char *BuiltinName = "";
2436 #define GET_GCC_BUILTIN_NAME
2437 #include "llvm/Intrinsics.gen"
2438 #undef GET_GCC_BUILTIN_NAME
2439 // If we handle it, don't lower it.
2440 if (BuiltinName[0]) break;
2442 // All other intrinsic calls we must lower.
2443 Instruction *Before = 0;
2444 if (CI != &BB->front())
2445 Before = prior(BasicBlock::iterator(CI));
2447 IL->LowerIntrinsicCall(CI);
2448 if (Before) { // Move iterator to instruction after call
2453 // If the intrinsic got lowered to another call, and that call has
2454 // a definition then we need to make sure its prototype is emitted
2455 // before any calls to it.
2456 if (CallInst *Call = dyn_cast<CallInst>(I))
2457 if (Function *NewF = Call->getCalledFunction())
2458 if (!NewF->isDeclaration())
2459 prototypesToGen.push_back(NewF);
2464 // We may have collected some prototypes to emit in the loop above.
2465 // Emit them now, before the function that uses them is emitted. But,
2466 // be careful not to emit them twice.
2467 std::vector<Function*>::iterator I = prototypesToGen.begin();
2468 std::vector<Function*>::iterator E = prototypesToGen.end();
2469 for ( ; I != E; ++I) {
2470 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2472 printFunctionSignature(*I, true);
2479 void CWriter::visitCallInst(CallInst &I) {
2480 //check if we have inline asm
2481 if (isInlineAsm(I)) {
2486 bool WroteCallee = false;
2488 // Handle intrinsic function calls first...
2489 if (Function *F = I.getCalledFunction())
2490 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2493 // If this is an intrinsic that directly corresponds to a GCC
2494 // builtin, we emit it here.
2495 const char *BuiltinName = "";
2496 #define GET_GCC_BUILTIN_NAME
2497 #include "llvm/Intrinsics.gen"
2498 #undef GET_GCC_BUILTIN_NAME
2499 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2505 case Intrinsic::vastart:
2508 Out << "va_start(*(va_list*)";
2509 writeOperand(I.getOperand(1));
2511 // Output the last argument to the enclosing function...
2512 if (I.getParent()->getParent()->arg_empty()) {
2513 cerr << "The C backend does not currently support zero "
2514 << "argument varargs functions, such as '"
2515 << I.getParent()->getParent()->getName() << "'!\n";
2518 writeOperand(--I.getParent()->getParent()->arg_end());
2521 case Intrinsic::vaend:
2522 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2523 Out << "0; va_end(*(va_list*)";
2524 writeOperand(I.getOperand(1));
2527 Out << "va_end(*(va_list*)0)";
2530 case Intrinsic::vacopy:
2532 Out << "va_copy(*(va_list*)";
2533 writeOperand(I.getOperand(1));
2534 Out << ", *(va_list*)";
2535 writeOperand(I.getOperand(2));
2538 case Intrinsic::returnaddress:
2539 Out << "__builtin_return_address(";
2540 writeOperand(I.getOperand(1));
2543 case Intrinsic::frameaddress:
2544 Out << "__builtin_frame_address(";
2545 writeOperand(I.getOperand(1));
2548 case Intrinsic::powi:
2549 Out << "__builtin_powi(";
2550 writeOperand(I.getOperand(1));
2552 writeOperand(I.getOperand(2));
2555 case Intrinsic::setjmp:
2556 Out << "setjmp(*(jmp_buf*)";
2557 writeOperand(I.getOperand(1));
2560 case Intrinsic::longjmp:
2561 Out << "longjmp(*(jmp_buf*)";
2562 writeOperand(I.getOperand(1));
2564 writeOperand(I.getOperand(2));
2567 case Intrinsic::prefetch:
2568 Out << "LLVM_PREFETCH((const void *)";
2569 writeOperand(I.getOperand(1));
2571 writeOperand(I.getOperand(2));
2573 writeOperand(I.getOperand(3));
2576 case Intrinsic::dbg_stoppoint: {
2577 // If we use writeOperand directly we get a "u" suffix which is rejected
2579 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2583 << " \"" << SPI.getDirectory()
2584 << SPI.getFileName() << "\"\n";
2590 Value *Callee = I.getCalledValue();
2592 const PointerType *PTy = cast<PointerType>(Callee->getType());
2593 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2595 // If this is a call to a struct-return function, assign to the first
2596 // parameter instead of passing it to the call.
2597 const ParamAttrsList *PAL = I.getParamAttrs();
2598 bool isStructRet = I.isStructReturn();
2601 writeOperand(I.getOperand(1));
2605 if (I.isTailCall()) Out << " /*tail*/ ";
2608 // If this is an indirect call to a struct return function, we need to cast
2610 bool NeedsCast = isStructRet && !isa<Function>(Callee);
2612 // GCC is a real PITA. It does not permit codegening casts of functions to
2613 // function pointers if they are in a call (it generates a trap instruction
2614 // instead!). We work around this by inserting a cast to void* in between
2615 // the function and the function pointer cast. Unfortunately, we can't just
2616 // form the constant expression here, because the folder will immediately
2619 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2620 // that void* and function pointers have the same size. :( To deal with this
2621 // in the common case, we handle casts where the number of arguments passed
2624 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2626 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2632 // Ok, just cast the pointer type.
2635 printType(Out, I.getCalledValue()->getType());
2637 printStructReturnPointerFunctionType(Out, PAL,
2638 cast<PointerType>(I.getCalledValue()->getType()));
2641 writeOperand(Callee);
2642 if (NeedsCast) Out << ')';
2647 unsigned NumDeclaredParams = FTy->getNumParams();
2649 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2651 if (isStructRet) { // Skip struct return argument.
2656 bool PrintedArg = false;
2658 for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
2659 if (PrintedArg) Out << ", ";
2660 if (ArgNo < NumDeclaredParams &&
2661 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2663 printType(Out, FTy->getParamType(ArgNo),
2664 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
2674 //This converts the llvm constraint string to something gcc is expecting.
2675 //TODO: work out platform independent constraints and factor those out
2676 // of the per target tables
2677 // handle multiple constraint codes
2678 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2680 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2682 const char** table = 0;
2684 //Grab the translation table from TargetAsmInfo if it exists
2687 const TargetMachineRegistry::entry* Match =
2688 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2690 //Per platform Target Machines don't exist, so create it
2691 // this must be done only once
2692 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2693 TAsm = TM->getTargetAsmInfo();
2697 table = TAsm->getAsmCBE();
2699 //Search the translation table if it exists
2700 for (int i = 0; table && table[i]; i += 2)
2701 if (c.Codes[0] == table[i])
2704 //default is identity
2708 //TODO: import logic from AsmPrinter.cpp
2709 static std::string gccifyAsm(std::string asmstr) {
2710 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2711 if (asmstr[i] == '\n')
2712 asmstr.replace(i, 1, "\\n");
2713 else if (asmstr[i] == '\t')
2714 asmstr.replace(i, 1, "\\t");
2715 else if (asmstr[i] == '$') {
2716 if (asmstr[i + 1] == '{') {
2717 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2718 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2719 std::string n = "%" +
2720 asmstr.substr(a + 1, b - a - 1) +
2721 asmstr.substr(i + 2, a - i - 2);
2722 asmstr.replace(i, b - i + 1, n);
2725 asmstr.replace(i, 1, "%");
2727 else if (asmstr[i] == '%')//grr
2728 { asmstr.replace(i, 1, "%%"); ++i;}
2733 //TODO: assumptions about what consume arguments from the call are likely wrong
2734 // handle communitivity
2735 void CWriter::visitInlineAsm(CallInst &CI) {
2736 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2737 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2738 std::vector<std::pair<std::string, Value*> > Input;
2739 std::vector<std::pair<std::string, Value*> > Output;
2740 std::string Clobber;
2741 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2742 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2743 E = Constraints.end(); I != E; ++I) {
2744 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2746 InterpretASMConstraint(*I);
2749 assert(0 && "Unknown asm constraint");
2751 case InlineAsm::isInput: {
2753 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2754 ++count; //consume arg
2758 case InlineAsm::isOutput: {
2760 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2761 count ? CI.getOperand(count) : &CI));
2762 ++count; //consume arg
2766 case InlineAsm::isClobber: {
2768 Clobber += ",\"" + c + "\"";
2774 //fix up the asm string for gcc
2775 std::string asmstr = gccifyAsm(as->getAsmString());
2777 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2779 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2780 E = Output.end(); I != E; ++I) {
2781 Out << "\"" << I->first << "\"(";
2782 writeOperandRaw(I->second);
2788 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2789 E = Input.end(); I != E; ++I) {
2790 Out << "\"" << I->first << "\"(";
2791 writeOperandRaw(I->second);
2797 Out << "\n :" << Clobber.substr(1);
2801 void CWriter::visitMallocInst(MallocInst &I) {
2802 assert(0 && "lowerallocations pass didn't work!");
2805 void CWriter::visitAllocaInst(AllocaInst &I) {
2807 printType(Out, I.getType());
2808 Out << ") alloca(sizeof(";
2809 printType(Out, I.getType()->getElementType());
2811 if (I.isArrayAllocation()) {
2813 writeOperand(I.getOperand(0));
2818 void CWriter::visitFreeInst(FreeInst &I) {
2819 assert(0 && "lowerallocations pass didn't work!");
2822 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2823 gep_type_iterator E) {
2824 bool HasImplicitAddress = false;
2825 // If accessing a global value with no indexing, avoid *(&GV) syndrome
2826 if (isa<GlobalValue>(Ptr)) {
2827 HasImplicitAddress = true;
2828 } else if (isDirectAlloca(Ptr)) {
2829 HasImplicitAddress = true;
2833 if (!HasImplicitAddress)
2834 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2836 writeOperandInternal(Ptr);
2840 const Constant *CI = dyn_cast<Constant>(I.getOperand());
2841 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2844 writeOperandInternal(Ptr);
2846 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2848 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2851 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2852 "Can only have implicit address with direct accessing");
2854 if (HasImplicitAddress) {
2856 } else if (CI && CI->isNullValue()) {
2857 gep_type_iterator TmpI = I; ++TmpI;
2859 // Print out the -> operator if possible...
2860 if (TmpI != E && isa<StructType>(*TmpI)) {
2861 Out << (HasImplicitAddress ? "." : "->");
2862 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2868 if (isa<StructType>(*I)) {
2869 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2872 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
2877 void CWriter::visitLoadInst(LoadInst &I) {
2879 if (I.isVolatile()) {
2881 printType(Out, I.getType(), false, "volatile*");
2885 writeOperand(I.getOperand(0));
2891 void CWriter::visitStoreInst(StoreInst &I) {
2893 if (I.isVolatile()) {
2895 printType(Out, I.getOperand(0)->getType(), false, " volatile*");
2898 writeOperand(I.getPointerOperand());
2899 if (I.isVolatile()) Out << ')';
2901 Value *Operand = I.getOperand(0);
2902 Constant *BitMask = 0;
2903 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
2904 if (!ITy->isPowerOf2ByteWidth())
2905 // We have a bit width that doesn't match an even power-of-2 byte
2906 // size. Consequently we must & the value with the type's bit mask
2907 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
2910 writeOperand(Operand);
2913 printConstant(BitMask);
2918 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2920 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2924 void CWriter::visitVAArgInst(VAArgInst &I) {
2925 Out << "va_arg(*(va_list*)";
2926 writeOperand(I.getOperand(0));
2928 printType(Out, I.getType());
2932 //===----------------------------------------------------------------------===//
2933 // External Interface declaration
2934 //===----------------------------------------------------------------------===//
2936 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2938 CodeGenFileType FileType,
2940 if (FileType != TargetMachine::AssemblyFile) return true;
2942 PM.add(createLowerGCPass());
2943 PM.add(createLowerAllocationsPass(true));
2944 PM.add(createLowerInvokePass());
2945 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
2946 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2947 PM.add(new CWriter(o));