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)
857 cerr << "CWriter Error: Unhandled constant expression: "
861 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
863 printType(Out, CPV->getType()); // sign doesn't matter
864 Out << ")/*UNDEF*/0)";
868 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
869 const Type* Ty = CI->getType();
870 if (Ty == Type::Int1Ty)
871 Out << (CI->getZExtValue() ? '1' : '0') ;
874 printSimpleType(Out, Ty, false) << ')';
875 if (CI->isMinValue(true))
876 Out << CI->getZExtValue() << 'u';
878 Out << CI->getSExtValue();
879 if (Ty->getPrimitiveSizeInBits() > 32)
886 switch (CPV->getType()->getTypeID()) {
887 case Type::FloatTyID:
888 case Type::DoubleTyID:
889 case Type::X86_FP80TyID:
890 case Type::PPC_FP128TyID:
891 case Type::FP128TyID: {
892 ConstantFP *FPC = cast<ConstantFP>(CPV);
893 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
894 if (I != FPConstantMap.end()) {
895 // Because of FP precision problems we must load from a stack allocated
896 // value that holds the value in hex.
897 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
898 FPC->getType() == Type::DoubleTy ? "double" :
900 << "*)&FPConstant" << I->second << ')';
902 assert(FPC->getType() == Type::FloatTy ||
903 FPC->getType() == Type::DoubleTy);
904 double V = FPC->getType() == Type::FloatTy ?
905 FPC->getValueAPF().convertToFloat() :
906 FPC->getValueAPF().convertToDouble();
910 // FIXME the actual NaN bits should be emitted.
911 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
913 const unsigned long QuietNaN = 0x7ff8UL;
914 //const unsigned long SignalNaN = 0x7ff4UL;
916 // We need to grab the first part of the FP #
919 uint64_t ll = DoubleToBits(V);
920 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
922 std::string Num(&Buffer[0], &Buffer[6]);
923 unsigned long Val = strtoul(Num.c_str(), 0, 16);
925 if (FPC->getType() == Type::FloatTy)
926 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
927 << Buffer << "\") /*nan*/ ";
929 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
930 << Buffer << "\") /*nan*/ ";
931 } else if (IsInf(V)) {
933 if (V < 0) Out << '-';
934 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
938 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
939 // Print out the constant as a floating point number.
941 sprintf(Buffer, "%a", V);
944 Num = ftostr(FPC->getValueAPF());
952 case Type::ArrayTyID:
953 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
954 const ArrayType *AT = cast<ArrayType>(CPV->getType());
956 if (AT->getNumElements()) {
958 Constant *CZ = Constant::getNullValue(AT->getElementType());
960 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
967 printConstantArray(cast<ConstantArray>(CPV));
971 case Type::VectorTyID:
972 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
973 const VectorType *AT = cast<VectorType>(CPV->getType());
975 if (AT->getNumElements()) {
977 Constant *CZ = Constant::getNullValue(AT->getElementType());
979 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
986 printConstantVector(cast<ConstantVector>(CPV));
990 case Type::StructTyID:
991 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
992 const StructType *ST = cast<StructType>(CPV->getType());
994 if (ST->getNumElements()) {
996 printConstant(Constant::getNullValue(ST->getElementType(0)));
997 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
999 printConstant(Constant::getNullValue(ST->getElementType(i)));
1005 if (CPV->getNumOperands()) {
1007 printConstant(cast<Constant>(CPV->getOperand(0)));
1008 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1010 printConstant(cast<Constant>(CPV->getOperand(i)));
1017 case Type::PointerTyID:
1018 if (isa<ConstantPointerNull>(CPV)) {
1020 printType(Out, CPV->getType()); // sign doesn't matter
1021 Out << ")/*NULL*/0)";
1023 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1029 cerr << "Unknown constant type: " << *CPV << "\n";
1034 // Some constant expressions need to be casted back to the original types
1035 // because their operands were casted to the expected type. This function takes
1036 // care of detecting that case and printing the cast for the ConstantExpr.
1037 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
1038 bool NeedsExplicitCast = false;
1039 const Type *Ty = CE->getOperand(0)->getType();
1040 bool TypeIsSigned = false;
1041 switch (CE->getOpcode()) {
1042 case Instruction::LShr:
1043 case Instruction::URem:
1044 case Instruction::UDiv: NeedsExplicitCast = true; break;
1045 case Instruction::AShr:
1046 case Instruction::SRem:
1047 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1048 case Instruction::SExt:
1050 NeedsExplicitCast = true;
1051 TypeIsSigned = true;
1053 case Instruction::ZExt:
1054 case Instruction::Trunc:
1055 case Instruction::FPTrunc:
1056 case Instruction::FPExt:
1057 case Instruction::UIToFP:
1058 case Instruction::SIToFP:
1059 case Instruction::FPToUI:
1060 case Instruction::FPToSI:
1061 case Instruction::PtrToInt:
1062 case Instruction::IntToPtr:
1063 case Instruction::BitCast:
1065 NeedsExplicitCast = true;
1069 if (NeedsExplicitCast) {
1071 if (Ty->isInteger() && Ty != Type::Int1Ty)
1072 printSimpleType(Out, Ty, TypeIsSigned);
1074 printType(Out, Ty); // not integer, sign doesn't matter
1077 return NeedsExplicitCast;
1080 // Print a constant assuming that it is the operand for a given Opcode. The
1081 // opcodes that care about sign need to cast their operands to the expected
1082 // type before the operation proceeds. This function does the casting.
1083 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1085 // Extract the operand's type, we'll need it.
1086 const Type* OpTy = CPV->getType();
1088 // Indicate whether to do the cast or not.
1089 bool shouldCast = false;
1090 bool typeIsSigned = false;
1092 // Based on the Opcode for which this Constant is being written, determine
1093 // the new type to which the operand should be casted by setting the value
1094 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1098 // for most instructions, it doesn't matter
1100 case Instruction::LShr:
1101 case Instruction::UDiv:
1102 case Instruction::URem:
1105 case Instruction::AShr:
1106 case Instruction::SDiv:
1107 case Instruction::SRem:
1109 typeIsSigned = true;
1113 // Write out the casted constant if we should, otherwise just write the
1117 printSimpleType(Out, OpTy, typeIsSigned);
1125 std::string CWriter::GetValueName(const Value *Operand) {
1128 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1129 std::string VarName;
1131 Name = Operand->getName();
1132 VarName.reserve(Name.capacity());
1134 for (std::string::iterator I = Name.begin(), E = Name.end();
1138 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1139 (ch >= '0' && ch <= '9') || ch == '_'))
1145 Name = "llvm_cbe_" + VarName;
1147 Name = Mang->getValueName(Operand);
1153 void CWriter::writeOperandInternal(Value *Operand) {
1154 if (Instruction *I = dyn_cast<Instruction>(Operand))
1155 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1156 // Should we inline this instruction to build a tree?
1163 Constant* CPV = dyn_cast<Constant>(Operand);
1165 if (CPV && !isa<GlobalValue>(CPV))
1168 Out << GetValueName(Operand);
1171 void CWriter::writeOperandRaw(Value *Operand) {
1172 Constant* CPV = dyn_cast<Constant>(Operand);
1173 if (CPV && !isa<GlobalValue>(CPV)) {
1176 Out << GetValueName(Operand);
1180 void CWriter::writeOperand(Value *Operand) {
1181 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1182 Out << "(&"; // Global variables are referenced as their addresses by llvm
1184 writeOperandInternal(Operand);
1186 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1190 // Some instructions need to have their result value casted back to the
1191 // original types because their operands were casted to the expected type.
1192 // This function takes care of detecting that case and printing the cast
1193 // for the Instruction.
1194 bool CWriter::writeInstructionCast(const Instruction &I) {
1195 const Type *Ty = I.getOperand(0)->getType();
1196 switch (I.getOpcode()) {
1197 case Instruction::LShr:
1198 case Instruction::URem:
1199 case Instruction::UDiv:
1201 printSimpleType(Out, Ty, false);
1204 case Instruction::AShr:
1205 case Instruction::SRem:
1206 case Instruction::SDiv:
1208 printSimpleType(Out, Ty, true);
1216 // Write the operand with a cast to another type based on the Opcode being used.
1217 // This will be used in cases where an instruction has specific type
1218 // requirements (usually signedness) for its operands.
1219 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1221 // Extract the operand's type, we'll need it.
1222 const Type* OpTy = Operand->getType();
1224 // Indicate whether to do the cast or not.
1225 bool shouldCast = false;
1227 // Indicate whether the cast should be to a signed type or not.
1228 bool castIsSigned = false;
1230 // Based on the Opcode for which this Operand is being written, determine
1231 // the new type to which the operand should be casted by setting the value
1232 // of OpTy. If we change OpTy, also set shouldCast to true.
1235 // for most instructions, it doesn't matter
1237 case Instruction::LShr:
1238 case Instruction::UDiv:
1239 case Instruction::URem: // Cast to unsigned first
1241 castIsSigned = false;
1243 case Instruction::GetElementPtr:
1244 case Instruction::AShr:
1245 case Instruction::SDiv:
1246 case Instruction::SRem: // Cast to signed first
1248 castIsSigned = true;
1252 // Write out the casted operand if we should, otherwise just write the
1256 printSimpleType(Out, OpTy, castIsSigned);
1258 writeOperand(Operand);
1261 writeOperand(Operand);
1264 // Write the operand with a cast to another type based on the icmp predicate
1266 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1267 // This has to do a cast to ensure the operand has the right signedness.
1268 // Also, if the operand is a pointer, we make sure to cast to an integer when
1269 // doing the comparison both for signedness and so that the C compiler doesn't
1270 // optimize things like "p < NULL" to false (p may contain an integer value
1272 bool shouldCast = Cmp.isRelational();
1274 // Write out the casted operand if we should, otherwise just write the
1277 writeOperand(Operand);
1281 // Should this be a signed comparison? If so, convert to signed.
1282 bool castIsSigned = Cmp.isSignedPredicate();
1284 // If the operand was a pointer, convert to a large integer type.
1285 const Type* OpTy = Operand->getType();
1286 if (isa<PointerType>(OpTy))
1287 OpTy = TD->getIntPtrType();
1290 printSimpleType(Out, OpTy, castIsSigned);
1292 writeOperand(Operand);
1296 // generateCompilerSpecificCode - This is where we add conditional compilation
1297 // directives to cater to specific compilers as need be.
1299 static void generateCompilerSpecificCode(std::ostream& Out) {
1300 // Alloca is hard to get, and we don't want to include stdlib.h here.
1301 Out << "/* get a declaration for alloca */\n"
1302 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1303 << "#define alloca(x) __builtin_alloca((x))\n"
1304 << "#define _alloca(x) __builtin_alloca((x))\n"
1305 << "#elif defined(__APPLE__)\n"
1306 << "extern void *__builtin_alloca(unsigned long);\n"
1307 << "#define alloca(x) __builtin_alloca(x)\n"
1308 << "#define longjmp _longjmp\n"
1309 << "#define setjmp _setjmp\n"
1310 << "#elif defined(__sun__)\n"
1311 << "#if defined(__sparcv9)\n"
1312 << "extern void *__builtin_alloca(unsigned long);\n"
1314 << "extern void *__builtin_alloca(unsigned int);\n"
1316 << "#define alloca(x) __builtin_alloca(x)\n"
1317 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1318 << "#define alloca(x) __builtin_alloca(x)\n"
1319 << "#elif defined(_MSC_VER)\n"
1320 << "#define inline _inline\n"
1321 << "#define alloca(x) _alloca(x)\n"
1323 << "#include <alloca.h>\n"
1326 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1327 // If we aren't being compiled with GCC, just drop these attributes.
1328 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1329 << "#define __attribute__(X)\n"
1332 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1333 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1334 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1335 << "#elif defined(__GNUC__)\n"
1336 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1338 << "#define __EXTERNAL_WEAK__\n"
1341 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1342 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1343 << "#define __ATTRIBUTE_WEAK__\n"
1344 << "#elif defined(__GNUC__)\n"
1345 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1347 << "#define __ATTRIBUTE_WEAK__\n"
1350 // Add hidden visibility support. FIXME: APPLE_CC?
1351 Out << "#if defined(__GNUC__)\n"
1352 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1355 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1356 // From the GCC documentation:
1358 // double __builtin_nan (const char *str)
1360 // This is an implementation of the ISO C99 function nan.
1362 // Since ISO C99 defines this function in terms of strtod, which we do
1363 // not implement, a description of the parsing is in order. The string is
1364 // parsed as by strtol; that is, the base is recognized by leading 0 or
1365 // 0x prefixes. The number parsed is placed in the significand such that
1366 // the least significant bit of the number is at the least significant
1367 // bit of the significand. The number is truncated to fit the significand
1368 // field provided. The significand is forced to be a quiet NaN.
1370 // This function, if given a string literal, is evaluated early enough
1371 // that it is considered a compile-time constant.
1373 // float __builtin_nanf (const char *str)
1375 // Similar to __builtin_nan, except the return type is float.
1377 // double __builtin_inf (void)
1379 // Similar to __builtin_huge_val, except a warning is generated if the
1380 // target floating-point format does not support infinities. This
1381 // function is suitable for implementing the ISO C99 macro INFINITY.
1383 // float __builtin_inff (void)
1385 // Similar to __builtin_inf, except the return type is float.
1386 Out << "#ifdef __GNUC__\n"
1387 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1388 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1389 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1390 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1391 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1392 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1393 << "#define LLVM_PREFETCH(addr,rw,locality) "
1394 "__builtin_prefetch(addr,rw,locality)\n"
1395 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1396 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1397 << "#define LLVM_ASM __asm__\n"
1399 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1400 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1401 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1402 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1403 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1404 << "#define LLVM_INFF 0.0F /* Float */\n"
1405 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1406 << "#define __ATTRIBUTE_CTOR__\n"
1407 << "#define __ATTRIBUTE_DTOR__\n"
1408 << "#define LLVM_ASM(X)\n"
1411 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1412 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1413 << "#define __builtin_stack_restore(X) /* noop */\n"
1416 // Output target-specific code that should be inserted into main.
1417 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1420 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1421 /// the StaticTors set.
1422 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1423 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1424 if (!InitList) return;
1426 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1427 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1428 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1430 if (CS->getOperand(1)->isNullValue())
1431 return; // Found a null terminator, exit printing.
1432 Constant *FP = CS->getOperand(1);
1433 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1435 FP = CE->getOperand(0);
1436 if (Function *F = dyn_cast<Function>(FP))
1437 StaticTors.insert(F);
1441 enum SpecialGlobalClass {
1443 GlobalCtors, GlobalDtors,
1447 /// getGlobalVariableClass - If this is a global that is specially recognized
1448 /// by LLVM, return a code that indicates how we should handle it.
1449 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1450 // If this is a global ctors/dtors list, handle it now.
1451 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1452 if (GV->getName() == "llvm.global_ctors")
1454 else if (GV->getName() == "llvm.global_dtors")
1458 // Otherwise, it it is other metadata, don't print it. This catches things
1459 // like debug information.
1460 if (GV->getSection() == "llvm.metadata")
1467 bool CWriter::doInitialization(Module &M) {
1471 TD = new TargetData(&M);
1472 IL = new IntrinsicLowering(*TD);
1473 IL->AddPrototypes(M);
1475 // Ensure that all structure types have names...
1476 Mang = new Mangler(M);
1477 Mang->markCharUnacceptable('.');
1479 // Keep track of which functions are static ctors/dtors so they can have
1480 // an attribute added to their prototypes.
1481 std::set<Function*> StaticCtors, StaticDtors;
1482 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1484 switch (getGlobalVariableClass(I)) {
1487 FindStaticTors(I, StaticCtors);
1490 FindStaticTors(I, StaticDtors);
1495 // get declaration for alloca
1496 Out << "/* Provide Declarations */\n";
1497 Out << "#include <stdarg.h>\n"; // Varargs support
1498 Out << "#include <setjmp.h>\n"; // Unwind support
1499 generateCompilerSpecificCode(Out);
1501 // Provide a definition for `bool' if not compiling with a C++ compiler.
1503 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1505 << "\n\n/* Support for floating point constants */\n"
1506 << "typedef unsigned long long ConstantDoubleTy;\n"
1507 << "typedef unsigned int ConstantFloatTy;\n"
1508 << "typedef struct { unsigned long long f1; unsigned short f2; "
1509 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1510 // This is used for both kinds of 128-bit long double; meaning differs.
1511 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1512 " ConstantFP128Ty;\n"
1513 << "\n\n/* Global Declarations */\n";
1515 // First output all the declarations for the program, because C requires
1516 // Functions & globals to be declared before they are used.
1519 // Loop over the symbol table, emitting all named constants...
1520 printModuleTypes(M.getTypeSymbolTable());
1522 // Global variable declarations...
1523 if (!M.global_empty()) {
1524 Out << "\n/* External Global Variable Declarations */\n";
1525 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1528 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
1530 else if (I->hasDLLImportLinkage())
1531 Out << "__declspec(dllimport) ";
1533 continue; // Internal Global
1535 // Thread Local Storage
1536 if (I->isThreadLocal())
1539 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1541 if (I->hasExternalWeakLinkage())
1542 Out << " __EXTERNAL_WEAK__";
1547 // Function declarations
1548 Out << "\n/* Function Declarations */\n";
1549 Out << "double fmod(double, double);\n"; // Support for FP rem
1550 Out << "float fmodf(float, float);\n";
1551 Out << "long double fmodl(long double, long double);\n";
1553 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1554 // Don't print declarations for intrinsic functions.
1555 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1556 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1557 if (I->hasExternalWeakLinkage())
1559 printFunctionSignature(I, true);
1560 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1561 Out << " __ATTRIBUTE_WEAK__";
1562 if (I->hasExternalWeakLinkage())
1563 Out << " __EXTERNAL_WEAK__";
1564 if (StaticCtors.count(I))
1565 Out << " __ATTRIBUTE_CTOR__";
1566 if (StaticDtors.count(I))
1567 Out << " __ATTRIBUTE_DTOR__";
1568 if (I->hasHiddenVisibility())
1569 Out << " __HIDDEN__";
1571 if (I->hasName() && I->getName()[0] == 1)
1572 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1578 // Output the global variable declarations
1579 if (!M.global_empty()) {
1580 Out << "\n\n/* Global Variable Declarations */\n";
1581 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1583 if (!I->isDeclaration()) {
1584 // Ignore special globals, such as debug info.
1585 if (getGlobalVariableClass(I))
1588 if (I->hasInternalLinkage())
1593 // Thread Local Storage
1594 if (I->isThreadLocal())
1597 printType(Out, I->getType()->getElementType(), false,
1600 if (I->hasLinkOnceLinkage())
1601 Out << " __attribute__((common))";
1602 else if (I->hasWeakLinkage())
1603 Out << " __ATTRIBUTE_WEAK__";
1604 else if (I->hasExternalWeakLinkage())
1605 Out << " __EXTERNAL_WEAK__";
1606 if (I->hasHiddenVisibility())
1607 Out << " __HIDDEN__";
1612 // Output the global variable definitions and contents...
1613 if (!M.global_empty()) {
1614 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1615 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1617 if (!I->isDeclaration()) {
1618 // Ignore special globals, such as debug info.
1619 if (getGlobalVariableClass(I))
1622 if (I->hasInternalLinkage())
1624 else if (I->hasDLLImportLinkage())
1625 Out << "__declspec(dllimport) ";
1626 else if (I->hasDLLExportLinkage())
1627 Out << "__declspec(dllexport) ";
1629 // Thread Local Storage
1630 if (I->isThreadLocal())
1633 printType(Out, I->getType()->getElementType(), false,
1635 if (I->hasLinkOnceLinkage())
1636 Out << " __attribute__((common))";
1637 else if (I->hasWeakLinkage())
1638 Out << " __ATTRIBUTE_WEAK__";
1640 if (I->hasHiddenVisibility())
1641 Out << " __HIDDEN__";
1643 // If the initializer is not null, emit the initializer. If it is null,
1644 // we try to avoid emitting large amounts of zeros. The problem with
1645 // this, however, occurs when the variable has weak linkage. In this
1646 // case, the assembler will complain about the variable being both weak
1647 // and common, so we disable this optimization.
1648 if (!I->getInitializer()->isNullValue()) {
1650 writeOperand(I->getInitializer());
1651 } else if (I->hasWeakLinkage()) {
1652 // We have to specify an initializer, but it doesn't have to be
1653 // complete. If the value is an aggregate, print out { 0 }, and let
1654 // the compiler figure out the rest of the zeros.
1656 if (isa<StructType>(I->getInitializer()->getType()) ||
1657 isa<ArrayType>(I->getInitializer()->getType()) ||
1658 isa<VectorType>(I->getInitializer()->getType())) {
1661 // Just print it out normally.
1662 writeOperand(I->getInitializer());
1670 Out << "\n\n/* Function Bodies */\n";
1672 // Emit some helper functions for dealing with FCMP instruction's
1674 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1675 Out << "return X == X && Y == Y; }\n";
1676 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1677 Out << "return X != X || Y != Y; }\n";
1678 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1679 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1680 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1681 Out << "return X != Y; }\n";
1682 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1683 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1684 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1685 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1686 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1687 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1688 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1689 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1690 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1691 Out << "return X == Y ; }\n";
1692 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1693 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1694 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1695 Out << "return X < Y ; }\n";
1696 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1697 Out << "return X > Y ; }\n";
1698 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1699 Out << "return X <= Y ; }\n";
1700 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1701 Out << "return X >= Y ; }\n";
1706 /// Output all floating point constants that cannot be printed accurately...
1707 void CWriter::printFloatingPointConstants(Function &F) {
1708 // Scan the module for floating point constants. If any FP constant is used
1709 // in the function, we want to redirect it here so that we do not depend on
1710 // the precision of the printed form, unless the printed form preserves
1713 static unsigned FPCounter = 0;
1714 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1716 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1717 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1718 !FPConstantMap.count(FPC)) {
1719 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1721 if (FPC->getType() == Type::DoubleTy) {
1722 double Val = FPC->getValueAPF().convertToDouble();
1723 uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
1724 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1725 << " = 0x" << std::hex << i << std::dec
1726 << "ULL; /* " << Val << " */\n";
1727 } else if (FPC->getType() == Type::FloatTy) {
1728 float Val = FPC->getValueAPF().convertToFloat();
1729 uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
1731 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1732 << " = 0x" << std::hex << i << std::dec
1733 << "U; /* " << Val << " */\n";
1734 } else if (FPC->getType() == Type::X86_FP80Ty) {
1735 // api needed to prevent premature destruction
1736 APInt api = FPC->getValueAPF().convertToAPInt();
1737 const uint64_t *p = api.getRawData();
1738 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
1739 << " = { 0x" << std::hex
1740 << ((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16)
1741 << ", 0x" << (uint16_t)(p[0] >> 48) << ",0,0,0"
1742 << "}; /* Long double constant */\n" << std::dec;
1743 } else if (FPC->getType() == Type::PPC_FP128Ty) {
1744 APInt api = FPC->getValueAPF().convertToAPInt();
1745 const uint64_t *p = api.getRawData();
1746 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
1747 << " = { 0x" << std::hex
1748 << p[0] << ", 0x" << p[1]
1749 << "}; /* Long double constant */\n" << std::dec;
1752 assert(0 && "Unknown float type!");
1759 /// printSymbolTable - Run through symbol table looking for type names. If a
1760 /// type name is found, emit its declaration...
1762 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1763 Out << "/* Helper union for bitcasts */\n";
1764 Out << "typedef union {\n";
1765 Out << " unsigned int Int32;\n";
1766 Out << " unsigned long long Int64;\n";
1767 Out << " float Float;\n";
1768 Out << " double Double;\n";
1769 Out << "} llvmBitCastUnion;\n";
1771 // We are only interested in the type plane of the symbol table.
1772 TypeSymbolTable::const_iterator I = TST.begin();
1773 TypeSymbolTable::const_iterator End = TST.end();
1775 // If there are no type names, exit early.
1776 if (I == End) return;
1778 // Print out forward declarations for structure types before anything else!
1779 Out << "/* Structure forward decls */\n";
1780 for (; I != End; ++I) {
1781 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1782 Out << Name << ";\n";
1783 TypeNames.insert(std::make_pair(I->second, Name));
1788 // Now we can print out typedefs. Above, we guaranteed that this can only be
1789 // for struct or opaque types.
1790 Out << "/* Typedefs */\n";
1791 for (I = TST.begin(); I != End; ++I) {
1792 std::string Name = "l_" + Mang->makeNameProper(I->first);
1794 printType(Out, I->second, false, Name);
1800 // Keep track of which structures have been printed so far...
1801 std::set<const StructType *> StructPrinted;
1803 // Loop over all structures then push them into the stack so they are
1804 // printed in the correct order.
1806 Out << "/* Structure contents */\n";
1807 for (I = TST.begin(); I != End; ++I)
1808 if (const StructType *STy = dyn_cast<StructType>(I->second))
1809 // Only print out used types!
1810 printContainedStructs(STy, StructPrinted);
1813 // Push the struct onto the stack and recursively push all structs
1814 // this one depends on.
1816 // TODO: Make this work properly with vector types
1818 void CWriter::printContainedStructs(const Type *Ty,
1819 std::set<const StructType*> &StructPrinted){
1820 // Don't walk through pointers.
1821 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1823 // Print all contained types first.
1824 for (Type::subtype_iterator I = Ty->subtype_begin(),
1825 E = Ty->subtype_end(); I != E; ++I)
1826 printContainedStructs(*I, StructPrinted);
1828 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1829 // Check to see if we have already printed this struct.
1830 if (StructPrinted.insert(STy).second) {
1831 // Print structure type out.
1832 std::string Name = TypeNames[STy];
1833 printType(Out, STy, false, Name, true);
1839 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1840 /// isStructReturn - Should this function actually return a struct by-value?
1841 bool isStructReturn = F->isStructReturn();
1843 if (F->hasInternalLinkage()) Out << "static ";
1844 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1845 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1846 switch (F->getCallingConv()) {
1847 case CallingConv::X86_StdCall:
1848 Out << "__stdcall ";
1850 case CallingConv::X86_FastCall:
1851 Out << "__fastcall ";
1855 // Loop over the arguments, printing them...
1856 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1857 const ParamAttrsList *PAL = F->getParamAttrs();
1859 std::stringstream FunctionInnards;
1861 // Print out the name...
1862 FunctionInnards << GetValueName(F) << '(';
1864 bool PrintedArg = false;
1865 if (!F->isDeclaration()) {
1866 if (!F->arg_empty()) {
1867 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1869 // If this is a struct-return function, don't print the hidden
1870 // struct-return argument.
1871 if (isStructReturn) {
1872 assert(I != E && "Invalid struct return function!");
1876 std::string ArgName;
1878 for (; I != E; ++I) {
1879 if (PrintedArg) FunctionInnards << ", ";
1880 if (I->hasName() || !Prototype)
1881 ArgName = GetValueName(I);
1884 printType(FunctionInnards, I->getType(),
1885 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt),
1892 // Loop over the arguments, printing them.
1893 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1895 // If this is a struct-return function, don't print the hidden
1896 // struct-return argument.
1897 if (isStructReturn) {
1898 assert(I != E && "Invalid struct return function!");
1903 for (; I != E; ++I) {
1904 if (PrintedArg) FunctionInnards << ", ";
1905 printType(FunctionInnards, *I,
1906 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
1912 // Finish printing arguments... if this is a vararg function, print the ...,
1913 // unless there are no known types, in which case, we just emit ().
1915 if (FT->isVarArg() && PrintedArg) {
1916 if (PrintedArg) FunctionInnards << ", ";
1917 FunctionInnards << "..."; // Output varargs portion of signature!
1918 } else if (!FT->isVarArg() && !PrintedArg) {
1919 FunctionInnards << "void"; // ret() -> ret(void) in C.
1921 FunctionInnards << ')';
1923 // Get the return tpe for the function.
1925 if (!isStructReturn)
1926 RetTy = F->getReturnType();
1928 // If this is a struct-return function, print the struct-return type.
1929 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1932 // Print out the return type and the signature built above.
1933 printType(Out, RetTy,
1934 /*isSigned=*/ PAL && PAL->paramHasAttr(0, ParamAttr::SExt),
1935 FunctionInnards.str());
1938 static inline bool isFPIntBitCast(const Instruction &I) {
1939 if (!isa<BitCastInst>(I))
1941 const Type *SrcTy = I.getOperand(0)->getType();
1942 const Type *DstTy = I.getType();
1943 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1944 (DstTy->isFloatingPoint() && SrcTy->isInteger());
1947 void CWriter::printFunction(Function &F) {
1948 /// isStructReturn - Should this function actually return a struct by-value?
1949 bool isStructReturn = F.isStructReturn();
1951 printFunctionSignature(&F, false);
1954 // If this is a struct return function, handle the result with magic.
1955 if (isStructReturn) {
1956 const Type *StructTy =
1957 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1959 printType(Out, StructTy, false, "StructReturn");
1960 Out << "; /* Struct return temporary */\n";
1963 printType(Out, F.arg_begin()->getType(), false,
1964 GetValueName(F.arg_begin()));
1965 Out << " = &StructReturn;\n";
1968 bool PrintedVar = false;
1970 // print local variable information for the function
1971 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
1972 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1974 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
1975 Out << "; /* Address-exposed local */\n";
1977 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1979 printType(Out, I->getType(), false, GetValueName(&*I));
1982 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1984 printType(Out, I->getType(), false,
1985 GetValueName(&*I)+"__PHI_TEMPORARY");
1990 // We need a temporary for the BitCast to use so it can pluck a value out
1991 // of a union to do the BitCast. This is separate from the need for a
1992 // variable to hold the result of the BitCast.
1993 if (isFPIntBitCast(*I)) {
1994 Out << " llvmBitCastUnion " << GetValueName(&*I)
1995 << "__BITCAST_TEMPORARY;\n";
2003 if (F.hasExternalLinkage() && F.getName() == "main")
2004 Out << " CODE_FOR_MAIN();\n";
2006 // print the basic blocks
2007 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2008 if (Loop *L = LI->getLoopFor(BB)) {
2009 if (L->getHeader() == BB && L->getParentLoop() == 0)
2012 printBasicBlock(BB);
2019 void CWriter::printLoop(Loop *L) {
2020 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2021 << "' to make GCC happy */\n";
2022 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2023 BasicBlock *BB = L->getBlocks()[i];
2024 Loop *BBLoop = LI->getLoopFor(BB);
2026 printBasicBlock(BB);
2027 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2030 Out << " } while (1); /* end of syntactic loop '"
2031 << L->getHeader()->getName() << "' */\n";
2034 void CWriter::printBasicBlock(BasicBlock *BB) {
2036 // Don't print the label for the basic block if there are no uses, or if
2037 // the only terminator use is the predecessor basic block's terminator.
2038 // We have to scan the use list because PHI nodes use basic blocks too but
2039 // do not require a label to be generated.
2041 bool NeedsLabel = false;
2042 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2043 if (isGotoCodeNecessary(*PI, BB)) {
2048 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2050 // Output all of the instructions in the basic block...
2051 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2053 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2054 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2063 // Don't emit prefix or suffix for the terminator...
2064 visit(*BB->getTerminator());
2068 // Specific Instruction type classes... note that all of the casts are
2069 // necessary because we use the instruction classes as opaque types...
2071 void CWriter::visitReturnInst(ReturnInst &I) {
2072 // If this is a struct return function, return the temporary struct.
2073 bool isStructReturn = I.getParent()->getParent()->isStructReturn();
2075 if (isStructReturn) {
2076 Out << " return StructReturn;\n";
2080 // Don't output a void return if this is the last basic block in the function
2081 if (I.getNumOperands() == 0 &&
2082 &*--I.getParent()->getParent()->end() == I.getParent() &&
2083 !I.getParent()->size() == 1) {
2088 if (I.getNumOperands()) {
2090 writeOperand(I.getOperand(0));
2095 void CWriter::visitSwitchInst(SwitchInst &SI) {
2098 writeOperand(SI.getOperand(0));
2099 Out << ") {\n default:\n";
2100 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2101 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2103 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2105 writeOperand(SI.getOperand(i));
2107 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2108 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2109 printBranchToBlock(SI.getParent(), Succ, 2);
2110 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2116 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2117 Out << " /*UNREACHABLE*/;\n";
2120 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2121 /// FIXME: This should be reenabled, but loop reordering safe!!
2124 if (next(Function::iterator(From)) != Function::iterator(To))
2125 return true; // Not the direct successor, we need a goto.
2127 //isa<SwitchInst>(From->getTerminator())
2129 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2134 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2135 BasicBlock *Successor,
2137 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2138 PHINode *PN = cast<PHINode>(I);
2139 // Now we have to do the printing.
2140 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2141 if (!isa<UndefValue>(IV)) {
2142 Out << std::string(Indent, ' ');
2143 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2145 Out << "; /* for PHI node */\n";
2150 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2152 if (isGotoCodeNecessary(CurBB, Succ)) {
2153 Out << std::string(Indent, ' ') << " goto ";
2159 // Branch instruction printing - Avoid printing out a branch to a basic block
2160 // that immediately succeeds the current one.
2162 void CWriter::visitBranchInst(BranchInst &I) {
2164 if (I.isConditional()) {
2165 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2167 writeOperand(I.getCondition());
2170 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2171 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2173 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2174 Out << " } else {\n";
2175 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2176 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2179 // First goto not necessary, assume second one is...
2181 writeOperand(I.getCondition());
2184 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2185 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2190 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2191 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2196 // PHI nodes get copied into temporary values at the end of predecessor basic
2197 // blocks. We now need to copy these temporary values into the REAL value for
2199 void CWriter::visitPHINode(PHINode &I) {
2201 Out << "__PHI_TEMPORARY";
2205 void CWriter::visitBinaryOperator(Instruction &I) {
2206 // binary instructions, shift instructions, setCond instructions.
2207 assert(!isa<PointerType>(I.getType()));
2209 // We must cast the results of binary operations which might be promoted.
2210 bool needsCast = false;
2211 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2212 || (I.getType() == Type::FloatTy)) {
2215 printType(Out, I.getType(), false);
2219 // If this is a negation operation, print it out as such. For FP, we don't
2220 // want to print "-0.0 - X".
2221 if (BinaryOperator::isNeg(&I)) {
2223 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2225 } else if (I.getOpcode() == Instruction::FRem) {
2226 // Output a call to fmod/fmodf instead of emitting a%b
2227 if (I.getType() == Type::FloatTy)
2229 else if (I.getType() == Type::DoubleTy)
2231 else // all 3 flavors of long double
2233 writeOperand(I.getOperand(0));
2235 writeOperand(I.getOperand(1));
2239 // Write out the cast of the instruction's value back to the proper type
2241 bool NeedsClosingParens = writeInstructionCast(I);
2243 // Certain instructions require the operand to be forced to a specific type
2244 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2245 // below for operand 1
2246 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2248 switch (I.getOpcode()) {
2249 case Instruction::Add: Out << " + "; break;
2250 case Instruction::Sub: Out << " - "; break;
2251 case Instruction::Mul: Out << " * "; break;
2252 case Instruction::URem:
2253 case Instruction::SRem:
2254 case Instruction::FRem: Out << " % "; break;
2255 case Instruction::UDiv:
2256 case Instruction::SDiv:
2257 case Instruction::FDiv: Out << " / "; break;
2258 case Instruction::And: Out << " & "; break;
2259 case Instruction::Or: Out << " | "; break;
2260 case Instruction::Xor: Out << " ^ "; break;
2261 case Instruction::Shl : Out << " << "; break;
2262 case Instruction::LShr:
2263 case Instruction::AShr: Out << " >> "; break;
2264 default: cerr << "Invalid operator type!" << I; abort();
2267 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2268 if (NeedsClosingParens)
2277 void CWriter::visitICmpInst(ICmpInst &I) {
2278 // We must cast the results of icmp which might be promoted.
2279 bool needsCast = false;
2281 // Write out the cast of the instruction's value back to the proper type
2283 bool NeedsClosingParens = writeInstructionCast(I);
2285 // Certain icmp predicate require the operand to be forced to a specific type
2286 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2287 // below for operand 1
2288 writeOperandWithCast(I.getOperand(0), I);
2290 switch (I.getPredicate()) {
2291 case ICmpInst::ICMP_EQ: Out << " == "; break;
2292 case ICmpInst::ICMP_NE: Out << " != "; break;
2293 case ICmpInst::ICMP_ULE:
2294 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2295 case ICmpInst::ICMP_UGE:
2296 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2297 case ICmpInst::ICMP_ULT:
2298 case ICmpInst::ICMP_SLT: Out << " < "; break;
2299 case ICmpInst::ICMP_UGT:
2300 case ICmpInst::ICMP_SGT: Out << " > "; break;
2301 default: cerr << "Invalid icmp predicate!" << I; abort();
2304 writeOperandWithCast(I.getOperand(1), I);
2305 if (NeedsClosingParens)
2313 void CWriter::visitFCmpInst(FCmpInst &I) {
2314 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2318 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2324 switch (I.getPredicate()) {
2325 default: assert(0 && "Illegal FCmp predicate");
2326 case FCmpInst::FCMP_ORD: op = "ord"; break;
2327 case FCmpInst::FCMP_UNO: op = "uno"; break;
2328 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2329 case FCmpInst::FCMP_UNE: op = "une"; break;
2330 case FCmpInst::FCMP_ULT: op = "ult"; break;
2331 case FCmpInst::FCMP_ULE: op = "ule"; break;
2332 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2333 case FCmpInst::FCMP_UGE: op = "uge"; break;
2334 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2335 case FCmpInst::FCMP_ONE: op = "one"; break;
2336 case FCmpInst::FCMP_OLT: op = "olt"; break;
2337 case FCmpInst::FCMP_OLE: op = "ole"; break;
2338 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2339 case FCmpInst::FCMP_OGE: op = "oge"; break;
2342 Out << "llvm_fcmp_" << op << "(";
2343 // Write the first operand
2344 writeOperand(I.getOperand(0));
2346 // Write the second operand
2347 writeOperand(I.getOperand(1));
2351 static const char * getFloatBitCastField(const Type *Ty) {
2352 switch (Ty->getTypeID()) {
2353 default: assert(0 && "Invalid Type");
2354 case Type::FloatTyID: return "Float";
2355 case Type::DoubleTyID: return "Double";
2356 case Type::IntegerTyID: {
2357 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2366 void CWriter::visitCastInst(CastInst &I) {
2367 const Type *DstTy = I.getType();
2368 const Type *SrcTy = I.getOperand(0)->getType();
2370 if (isFPIntBitCast(I)) {
2371 // These int<->float and long<->double casts need to be handled specially
2372 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2373 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2374 writeOperand(I.getOperand(0));
2375 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2376 << getFloatBitCastField(I.getType());
2378 printCast(I.getOpcode(), SrcTy, DstTy);
2379 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
2380 // Make sure we really get a sext from bool by subtracing the bool from 0
2383 writeOperand(I.getOperand(0));
2384 if (DstTy == Type::Int1Ty &&
2385 (I.getOpcode() == Instruction::Trunc ||
2386 I.getOpcode() == Instruction::FPToUI ||
2387 I.getOpcode() == Instruction::FPToSI ||
2388 I.getOpcode() == Instruction::PtrToInt)) {
2389 // Make sure we really get a trunc to bool by anding the operand with 1
2396 void CWriter::visitSelectInst(SelectInst &I) {
2398 writeOperand(I.getCondition());
2400 writeOperand(I.getTrueValue());
2402 writeOperand(I.getFalseValue());
2407 void CWriter::lowerIntrinsics(Function &F) {
2408 // This is used to keep track of intrinsics that get generated to a lowered
2409 // function. We must generate the prototypes before the function body which
2410 // will only be expanded on first use (by the loop below).
2411 std::vector<Function*> prototypesToGen;
2413 // Examine all the instructions in this function to find the intrinsics that
2414 // need to be lowered.
2415 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2416 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2417 if (CallInst *CI = dyn_cast<CallInst>(I++))
2418 if (Function *F = CI->getCalledFunction())
2419 switch (F->getIntrinsicID()) {
2420 case Intrinsic::not_intrinsic:
2421 case Intrinsic::vastart:
2422 case Intrinsic::vacopy:
2423 case Intrinsic::vaend:
2424 case Intrinsic::returnaddress:
2425 case Intrinsic::frameaddress:
2426 case Intrinsic::setjmp:
2427 case Intrinsic::longjmp:
2428 case Intrinsic::prefetch:
2429 case Intrinsic::dbg_stoppoint:
2430 case Intrinsic::powi:
2431 // We directly implement these intrinsics
2434 // If this is an intrinsic that directly corresponds to a GCC
2435 // builtin, we handle it.
2436 const char *BuiltinName = "";
2437 #define GET_GCC_BUILTIN_NAME
2438 #include "llvm/Intrinsics.gen"
2439 #undef GET_GCC_BUILTIN_NAME
2440 // If we handle it, don't lower it.
2441 if (BuiltinName[0]) break;
2443 // All other intrinsic calls we must lower.
2444 Instruction *Before = 0;
2445 if (CI != &BB->front())
2446 Before = prior(BasicBlock::iterator(CI));
2448 IL->LowerIntrinsicCall(CI);
2449 if (Before) { // Move iterator to instruction after call
2454 // If the intrinsic got lowered to another call, and that call has
2455 // a definition then we need to make sure its prototype is emitted
2456 // before any calls to it.
2457 if (CallInst *Call = dyn_cast<CallInst>(I))
2458 if (Function *NewF = Call->getCalledFunction())
2459 if (!NewF->isDeclaration())
2460 prototypesToGen.push_back(NewF);
2465 // We may have collected some prototypes to emit in the loop above.
2466 // Emit them now, before the function that uses them is emitted. But,
2467 // be careful not to emit them twice.
2468 std::vector<Function*>::iterator I = prototypesToGen.begin();
2469 std::vector<Function*>::iterator E = prototypesToGen.end();
2470 for ( ; I != E; ++I) {
2471 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2473 printFunctionSignature(*I, true);
2480 void CWriter::visitCallInst(CallInst &I) {
2481 //check if we have inline asm
2482 if (isInlineAsm(I)) {
2487 bool WroteCallee = false;
2489 // Handle intrinsic function calls first...
2490 if (Function *F = I.getCalledFunction())
2491 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2494 // If this is an intrinsic that directly corresponds to a GCC
2495 // builtin, we emit it here.
2496 const char *BuiltinName = "";
2497 #define GET_GCC_BUILTIN_NAME
2498 #include "llvm/Intrinsics.gen"
2499 #undef GET_GCC_BUILTIN_NAME
2500 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2506 case Intrinsic::vastart:
2509 Out << "va_start(*(va_list*)";
2510 writeOperand(I.getOperand(1));
2512 // Output the last argument to the enclosing function...
2513 if (I.getParent()->getParent()->arg_empty()) {
2514 cerr << "The C backend does not currently support zero "
2515 << "argument varargs functions, such as '"
2516 << I.getParent()->getParent()->getName() << "'!\n";
2519 writeOperand(--I.getParent()->getParent()->arg_end());
2522 case Intrinsic::vaend:
2523 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2524 Out << "0; va_end(*(va_list*)";
2525 writeOperand(I.getOperand(1));
2528 Out << "va_end(*(va_list*)0)";
2531 case Intrinsic::vacopy:
2533 Out << "va_copy(*(va_list*)";
2534 writeOperand(I.getOperand(1));
2535 Out << ", *(va_list*)";
2536 writeOperand(I.getOperand(2));
2539 case Intrinsic::returnaddress:
2540 Out << "__builtin_return_address(";
2541 writeOperand(I.getOperand(1));
2544 case Intrinsic::frameaddress:
2545 Out << "__builtin_frame_address(";
2546 writeOperand(I.getOperand(1));
2549 case Intrinsic::powi:
2550 Out << "__builtin_powi(";
2551 writeOperand(I.getOperand(1));
2553 writeOperand(I.getOperand(2));
2556 case Intrinsic::setjmp:
2557 Out << "setjmp(*(jmp_buf*)";
2558 writeOperand(I.getOperand(1));
2561 case Intrinsic::longjmp:
2562 Out << "longjmp(*(jmp_buf*)";
2563 writeOperand(I.getOperand(1));
2565 writeOperand(I.getOperand(2));
2568 case Intrinsic::prefetch:
2569 Out << "LLVM_PREFETCH((const void *)";
2570 writeOperand(I.getOperand(1));
2572 writeOperand(I.getOperand(2));
2574 writeOperand(I.getOperand(3));
2577 case Intrinsic::stacksave:
2578 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
2579 // to work around GCC bugs (see PR1809).
2580 Out << "0; *((void**)&" << GetValueName(&I)
2581 << ") = __builtin_stack_save()";
2583 case Intrinsic::dbg_stoppoint: {
2584 // If we use writeOperand directly we get a "u" suffix which is rejected
2586 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2590 << " \"" << SPI.getDirectory()
2591 << SPI.getFileName() << "\"\n";
2597 Value *Callee = I.getCalledValue();
2599 const PointerType *PTy = cast<PointerType>(Callee->getType());
2600 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2602 // If this is a call to a struct-return function, assign to the first
2603 // parameter instead of passing it to the call.
2604 const ParamAttrsList *PAL = I.getParamAttrs();
2605 bool isStructRet = I.isStructReturn();
2608 writeOperand(I.getOperand(1));
2612 if (I.isTailCall()) Out << " /*tail*/ ";
2615 // If this is an indirect call to a struct return function, we need to cast
2617 bool NeedsCast = isStructRet && !isa<Function>(Callee);
2619 // GCC is a real PITA. It does not permit codegening casts of functions to
2620 // function pointers if they are in a call (it generates a trap instruction
2621 // instead!). We work around this by inserting a cast to void* in between
2622 // the function and the function pointer cast. Unfortunately, we can't just
2623 // form the constant expression here, because the folder will immediately
2626 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2627 // that void* and function pointers have the same size. :( To deal with this
2628 // in the common case, we handle casts where the number of arguments passed
2631 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2633 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2639 // Ok, just cast the pointer type.
2642 printType(Out, I.getCalledValue()->getType());
2644 printStructReturnPointerFunctionType(Out, PAL,
2645 cast<PointerType>(I.getCalledValue()->getType()));
2648 writeOperand(Callee);
2649 if (NeedsCast) Out << ')';
2654 unsigned NumDeclaredParams = FTy->getNumParams();
2656 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2658 if (isStructRet) { // Skip struct return argument.
2663 bool PrintedArg = false;
2665 for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
2666 if (PrintedArg) Out << ", ";
2667 if (ArgNo < NumDeclaredParams &&
2668 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2670 printType(Out, FTy->getParamType(ArgNo),
2671 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
2681 //This converts the llvm constraint string to something gcc is expecting.
2682 //TODO: work out platform independent constraints and factor those out
2683 // of the per target tables
2684 // handle multiple constraint codes
2685 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2687 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2689 const char** table = 0;
2691 //Grab the translation table from TargetAsmInfo if it exists
2694 const TargetMachineRegistry::entry* Match =
2695 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2697 //Per platform Target Machines don't exist, so create it
2698 // this must be done only once
2699 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2700 TAsm = TM->getTargetAsmInfo();
2704 table = TAsm->getAsmCBE();
2706 //Search the translation table if it exists
2707 for (int i = 0; table && table[i]; i += 2)
2708 if (c.Codes[0] == table[i])
2711 //default is identity
2715 //TODO: import logic from AsmPrinter.cpp
2716 static std::string gccifyAsm(std::string asmstr) {
2717 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2718 if (asmstr[i] == '\n')
2719 asmstr.replace(i, 1, "\\n");
2720 else if (asmstr[i] == '\t')
2721 asmstr.replace(i, 1, "\\t");
2722 else if (asmstr[i] == '$') {
2723 if (asmstr[i + 1] == '{') {
2724 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2725 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2726 std::string n = "%" +
2727 asmstr.substr(a + 1, b - a - 1) +
2728 asmstr.substr(i + 2, a - i - 2);
2729 asmstr.replace(i, b - i + 1, n);
2732 asmstr.replace(i, 1, "%");
2734 else if (asmstr[i] == '%')//grr
2735 { asmstr.replace(i, 1, "%%"); ++i;}
2740 //TODO: assumptions about what consume arguments from the call are likely wrong
2741 // handle communitivity
2742 void CWriter::visitInlineAsm(CallInst &CI) {
2743 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2744 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2745 std::vector<std::pair<std::string, Value*> > Input;
2746 std::vector<std::pair<std::string, Value*> > Output;
2747 std::string Clobber;
2748 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2749 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2750 E = Constraints.end(); I != E; ++I) {
2751 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2753 InterpretASMConstraint(*I);
2756 assert(0 && "Unknown asm constraint");
2758 case InlineAsm::isInput: {
2760 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2761 ++count; //consume arg
2765 case InlineAsm::isOutput: {
2767 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2768 count ? CI.getOperand(count) : &CI));
2769 ++count; //consume arg
2773 case InlineAsm::isClobber: {
2775 Clobber += ",\"" + c + "\"";
2781 //fix up the asm string for gcc
2782 std::string asmstr = gccifyAsm(as->getAsmString());
2784 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2786 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2787 E = Output.end(); I != E; ++I) {
2788 Out << "\"" << I->first << "\"(";
2789 writeOperandRaw(I->second);
2795 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2796 E = Input.end(); I != E; ++I) {
2797 Out << "\"" << I->first << "\"(";
2798 writeOperandRaw(I->second);
2804 Out << "\n :" << Clobber.substr(1);
2808 void CWriter::visitMallocInst(MallocInst &I) {
2809 assert(0 && "lowerallocations pass didn't work!");
2812 void CWriter::visitAllocaInst(AllocaInst &I) {
2814 printType(Out, I.getType());
2815 Out << ") alloca(sizeof(";
2816 printType(Out, I.getType()->getElementType());
2818 if (I.isArrayAllocation()) {
2820 writeOperand(I.getOperand(0));
2825 void CWriter::visitFreeInst(FreeInst &I) {
2826 assert(0 && "lowerallocations pass didn't work!");
2829 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2830 gep_type_iterator E) {
2831 bool HasImplicitAddress = false;
2832 // If accessing a global value with no indexing, avoid *(&GV) syndrome
2833 if (isa<GlobalValue>(Ptr)) {
2834 HasImplicitAddress = true;
2835 } else if (isDirectAlloca(Ptr)) {
2836 HasImplicitAddress = true;
2840 if (!HasImplicitAddress)
2841 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2843 writeOperandInternal(Ptr);
2847 const Constant *CI = dyn_cast<Constant>(I.getOperand());
2848 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2851 writeOperandInternal(Ptr);
2853 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2855 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2858 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2859 "Can only have implicit address with direct accessing");
2861 if (HasImplicitAddress) {
2863 } else if (CI && CI->isNullValue()) {
2864 gep_type_iterator TmpI = I; ++TmpI;
2866 // Print out the -> operator if possible...
2867 if (TmpI != E && isa<StructType>(*TmpI)) {
2868 Out << (HasImplicitAddress ? "." : "->");
2869 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2875 if (isa<StructType>(*I)) {
2876 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2879 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
2884 void CWriter::visitLoadInst(LoadInst &I) {
2886 if (I.isVolatile()) {
2888 printType(Out, I.getType(), false, "volatile*");
2892 writeOperand(I.getOperand(0));
2898 void CWriter::visitStoreInst(StoreInst &I) {
2900 if (I.isVolatile()) {
2902 printType(Out, I.getOperand(0)->getType(), false, " volatile*");
2905 writeOperand(I.getPointerOperand());
2906 if (I.isVolatile()) Out << ')';
2908 Value *Operand = I.getOperand(0);
2909 Constant *BitMask = 0;
2910 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
2911 if (!ITy->isPowerOf2ByteWidth())
2912 // We have a bit width that doesn't match an even power-of-2 byte
2913 // size. Consequently we must & the value with the type's bit mask
2914 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
2917 writeOperand(Operand);
2920 printConstant(BitMask);
2925 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2927 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2931 void CWriter::visitVAArgInst(VAArgInst &I) {
2932 Out << "va_arg(*(va_list*)";
2933 writeOperand(I.getOperand(0));
2935 printType(Out, I.getType());
2939 //===----------------------------------------------------------------------===//
2940 // External Interface declaration
2941 //===----------------------------------------------------------------------===//
2943 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2945 CodeGenFileType FileType,
2947 if (FileType != TargetMachine::AssemblyFile) return true;
2949 PM.add(createLowerGCPass());
2950 PM.add(createLowerAllocationsPass(true));
2951 PM.add(createLowerInvokePass());
2952 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
2953 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2954 PM.add(new CWriter(o));