1 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Passes.h"
32 #include "llvm/CodeGen/IntrinsicLowering.h"
33 #include "llvm/Transforms/Scalar.h"
34 #include "llvm/Target/TargetMachineRegistry.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/InstVisitor.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Config/config.h"
52 // Register the target.
53 RegisterTarget<CTargetMachine> X("c", " C backend");
55 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
56 /// any unnamed structure types that are used by the program, and merges
57 /// external functions with the same name.
59 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
62 CBackendNameAllUsedStructsAndMergeFunctions()
63 : ModulePass((intptr_t)&ID) {}
64 void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<FindUsedTypes>();
68 virtual const char *getPassName() const {
69 return "C backend type canonicalizer";
72 virtual bool runOnModule(Module &M);
75 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
77 /// CWriter - This class is the main chunk of code that converts an LLVM
78 /// module to a C translation unit.
79 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
81 IntrinsicLowering *IL;
84 const Module *TheModule;
85 const TargetAsmInfo* TAsm;
87 std::map<const Type *, std::string> TypeNames;
88 std::map<const ConstantFP *, unsigned> FPConstantMap;
89 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
93 CWriter(std::ostream &o)
94 : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0),
95 TheModule(0), TAsm(0), TD(0) {}
97 virtual const char *getPassName() const { return "C backend"; }
99 void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<LoopInfo>();
101 AU.setPreservesAll();
104 virtual bool doInitialization(Module &M);
106 bool runOnFunction(Function &F) {
107 LI = &getAnalysis<LoopInfo>();
109 // Get rid of intrinsics we can't handle.
112 // Output all floating point constants that cannot be printed accurately.
113 printFloatingPointConstants(F);
116 FPConstantMap.clear();
120 virtual bool doFinalization(Module &M) {
127 std::ostream &printType(std::ostream &Out, const Type *Ty,
128 bool isSigned = false,
129 const std::string &VariableName = "",
130 bool IgnoreName = false,
131 const ParamAttrsList *PAL = 0);
132 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
134 const std::string &NameSoFar = "");
136 void printStructReturnPointerFunctionType(std::ostream &Out,
137 const ParamAttrsList *PAL,
138 const PointerType *Ty);
140 void writeOperand(Value *Operand);
141 void writeOperandRaw(Value *Operand);
142 void writeOperandInternal(Value *Operand);
143 void writeOperandWithCast(Value* Operand, unsigned Opcode);
144 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
145 bool writeInstructionCast(const Instruction &I);
148 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
150 void lowerIntrinsics(Function &F);
152 void printModule(Module *M);
153 void printModuleTypes(const TypeSymbolTable &ST);
154 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
155 void printFloatingPointConstants(Function &F);
156 void printFunctionSignature(const Function *F, bool Prototype);
158 void printFunction(Function &);
159 void printBasicBlock(BasicBlock *BB);
160 void printLoop(Loop *L);
162 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
163 void printConstant(Constant *CPV);
164 void printConstantWithCast(Constant *CPV, unsigned Opcode);
165 bool printConstExprCast(const ConstantExpr *CE);
166 void printConstantArray(ConstantArray *CPA);
167 void printConstantVector(ConstantVector *CP);
169 // isInlinableInst - Attempt to inline instructions into their uses to build
170 // trees as much as possible. To do this, we have to consistently decide
171 // what is acceptable to inline, so that variable declarations don't get
172 // printed and an extra copy of the expr is not emitted.
174 static bool isInlinableInst(const Instruction &I) {
175 // Always inline cmp instructions, even if they are shared by multiple
176 // expressions. GCC generates horrible code if we don't.
180 // Must be an expression, must be used exactly once. If it is dead, we
181 // emit it inline where it would go.
182 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
183 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
184 isa<LoadInst>(I) || isa<VAArgInst>(I))
185 // Don't inline a load across a store or other bad things!
188 // Must not be used in inline asm
189 if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
191 // Only inline instruction it if it's use is in the same BB as the inst.
192 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
195 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
196 // variables which are accessed with the & operator. This causes GCC to
197 // generate significantly better code than to emit alloca calls directly.
199 static const AllocaInst *isDirectAlloca(const Value *V) {
200 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
201 if (!AI) return false;
202 if (AI->isArrayAllocation())
203 return 0; // FIXME: we can also inline fixed size array allocas!
204 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
209 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
210 static bool isInlineAsm(const Instruction& I) {
211 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
216 // Instruction visitation functions
217 friend class InstVisitor<CWriter>;
219 void visitReturnInst(ReturnInst &I);
220 void visitBranchInst(BranchInst &I);
221 void visitSwitchInst(SwitchInst &I);
222 void visitInvokeInst(InvokeInst &I) {
223 assert(0 && "Lowerinvoke pass didn't work!");
226 void visitUnwindInst(UnwindInst &I) {
227 assert(0 && "Lowerinvoke pass didn't work!");
229 void visitUnreachableInst(UnreachableInst &I);
231 void visitPHINode(PHINode &I);
232 void visitBinaryOperator(Instruction &I);
233 void visitICmpInst(ICmpInst &I);
234 void visitFCmpInst(FCmpInst &I);
236 void visitCastInst (CastInst &I);
237 void visitSelectInst(SelectInst &I);
238 void visitCallInst (CallInst &I);
239 void visitInlineAsm(CallInst &I);
241 void visitMallocInst(MallocInst &I);
242 void visitAllocaInst(AllocaInst &I);
243 void visitFreeInst (FreeInst &I);
244 void visitLoadInst (LoadInst &I);
245 void visitStoreInst (StoreInst &I);
246 void visitGetElementPtrInst(GetElementPtrInst &I);
247 void visitVAArgInst (VAArgInst &I);
249 void visitInstruction(Instruction &I) {
250 cerr << "C Writer does not know about " << I;
254 void outputLValue(Instruction *I) {
255 Out << " " << GetValueName(I) << " = ";
258 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
259 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
260 BasicBlock *Successor, unsigned Indent);
261 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
263 void printIndexingExpression(Value *Ptr, gep_type_iterator I,
264 gep_type_iterator E);
266 std::string GetValueName(const Value *Operand);
270 char CWriter::ID = 0;
272 /// This method inserts names for any unnamed structure types that are used by
273 /// the program, and removes names from structure types that are not used by the
276 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
277 // Get a set of types that are used by the program...
278 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
280 // Loop over the module symbol table, removing types from UT that are
281 // already named, and removing names for types that are not used.
283 TypeSymbolTable &TST = M.getTypeSymbolTable();
284 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
286 TypeSymbolTable::iterator I = TI++;
288 // If this isn't a struct type, remove it from our set of types to name.
289 // This simplifies emission later.
290 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
293 // If this is not used, remove it from the symbol table.
294 std::set<const Type *>::iterator UTI = UT.find(I->second);
298 UT.erase(UTI); // Only keep one name for this type.
302 // UT now contains types that are not named. Loop over it, naming
305 bool Changed = false;
306 unsigned RenameCounter = 0;
307 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
309 if (const StructType *ST = dyn_cast<StructType>(*I)) {
310 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
316 // Loop over all external functions and globals. If we have two with
317 // identical names, merge them.
318 // FIXME: This code should disappear when we don't allow values with the same
319 // names when they have different types!
320 std::map<std::string, GlobalValue*> ExtSymbols;
321 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
323 if (GV->isDeclaration() && GV->hasName()) {
324 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
325 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
327 // Found a conflict, replace this global with the previous one.
328 GlobalValue *OldGV = X.first->second;
329 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
330 GV->eraseFromParent();
335 // Do the same for globals.
336 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
338 GlobalVariable *GV = I++;
339 if (GV->isDeclaration() && GV->hasName()) {
340 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
341 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
343 // Found a conflict, replace this global with the previous one.
344 GlobalValue *OldGV = X.first->second;
345 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
346 GV->eraseFromParent();
355 /// printStructReturnPointerFunctionType - This is like printType for a struct
356 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
357 /// print it as "Struct (*)(...)", for struct return functions.
358 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
359 const ParamAttrsList *PAL,
360 const PointerType *TheTy) {
361 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
362 std::stringstream FunctionInnards;
363 FunctionInnards << " (*) (";
364 bool PrintedType = false;
366 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
367 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
369 for (++I, ++Idx; I != E; ++I, ++Idx) {
371 FunctionInnards << ", ";
372 const Type *ArgTy = *I;
373 printType(FunctionInnards, ArgTy,
374 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
377 if (FTy->isVarArg()) {
379 FunctionInnards << ", ...";
380 } else if (!PrintedType) {
381 FunctionInnards << "void";
383 FunctionInnards << ')';
384 std::string tstr = FunctionInnards.str();
385 printType(Out, RetTy,
386 /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
390 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
391 const std::string &NameSoFar) {
392 assert((Ty->isPrimitiveType() || Ty->isInteger()) &&
393 "Invalid type for printSimpleType");
394 switch (Ty->getTypeID()) {
395 case Type::VoidTyID: return Out << "void " << NameSoFar;
396 case Type::IntegerTyID: {
397 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
399 return Out << "bool " << NameSoFar;
400 else if (NumBits <= 8)
401 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
402 else if (NumBits <= 16)
403 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
404 else if (NumBits <= 32)
405 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
407 assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
408 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
411 case Type::FloatTyID: return Out << "float " << NameSoFar;
412 case Type::DoubleTyID: return Out << "double " << NameSoFar;
413 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
414 // present matches host 'long double'.
415 case Type::X86_FP80TyID:
416 case Type::PPC_FP128TyID:
417 case Type::FP128TyID: return Out << "long double " << NameSoFar;
419 cerr << "Unknown primitive type: " << *Ty << "\n";
424 // Pass the Type* and the variable name and this prints out the variable
427 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
428 bool isSigned, const std::string &NameSoFar,
429 bool IgnoreName, const ParamAttrsList* PAL) {
430 if (Ty->isPrimitiveType() || Ty->isInteger()) {
431 printSimpleType(Out, Ty, isSigned, NameSoFar);
435 // Check to see if the type is named.
436 if (!IgnoreName || isa<OpaqueType>(Ty)) {
437 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
438 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
441 switch (Ty->getTypeID()) {
442 case Type::FunctionTyID: {
443 const FunctionType *FTy = cast<FunctionType>(Ty);
444 std::stringstream FunctionInnards;
445 FunctionInnards << " (" << NameSoFar << ") (";
447 for (FunctionType::param_iterator I = FTy->param_begin(),
448 E = FTy->param_end(); I != E; ++I) {
449 if (I != FTy->param_begin())
450 FunctionInnards << ", ";
451 printType(FunctionInnards, *I,
452 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt), "");
455 if (FTy->isVarArg()) {
456 if (FTy->getNumParams())
457 FunctionInnards << ", ...";
458 } else if (!FTy->getNumParams()) {
459 FunctionInnards << "void";
461 FunctionInnards << ')';
462 std::string tstr = FunctionInnards.str();
463 printType(Out, FTy->getReturnType(),
464 /*isSigned=*/PAL && PAL->paramHasAttr(0, ParamAttr::SExt), tstr);
467 case Type::StructTyID: {
468 const StructType *STy = cast<StructType>(Ty);
469 Out << NameSoFar + " {\n";
471 for (StructType::element_iterator I = STy->element_begin(),
472 E = STy->element_end(); I != E; ++I) {
474 printType(Out, *I, false, "field" + utostr(Idx++));
479 Out << " __attribute__ ((packed))";
483 case Type::PointerTyID: {
484 const PointerType *PTy = cast<PointerType>(Ty);
485 std::string ptrName = "*" + NameSoFar;
487 if (isa<ArrayType>(PTy->getElementType()) ||
488 isa<VectorType>(PTy->getElementType()))
489 ptrName = "(" + ptrName + ")";
491 return printType(Out, PTy->getElementType(), false, ptrName);
494 case Type::ArrayTyID: {
495 const ArrayType *ATy = cast<ArrayType>(Ty);
496 unsigned NumElements = ATy->getNumElements();
497 if (NumElements == 0) NumElements = 1;
498 return printType(Out, ATy->getElementType(), false,
499 NameSoFar + "[" + utostr(NumElements) + "]");
502 case Type::VectorTyID: {
503 const VectorType *PTy = cast<VectorType>(Ty);
504 unsigned NumElements = PTy->getNumElements();
505 if (NumElements == 0) NumElements = 1;
506 return printType(Out, PTy->getElementType(), false,
507 NameSoFar + "[" + utostr(NumElements) + "]");
510 case Type::OpaqueTyID: {
511 static int Count = 0;
512 std::string TyName = "struct opaque_" + itostr(Count++);
513 assert(TypeNames.find(Ty) == TypeNames.end());
514 TypeNames[Ty] = TyName;
515 return Out << TyName << ' ' << NameSoFar;
518 assert(0 && "Unhandled case in getTypeProps!");
525 void CWriter::printConstantArray(ConstantArray *CPA) {
527 // As a special case, print the array as a string if it is an array of
528 // ubytes or an array of sbytes with positive values.
530 const Type *ETy = CPA->getType()->getElementType();
531 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
533 // Make sure the last character is a null char, as automatically added by C
534 if (isString && (CPA->getNumOperands() == 0 ||
535 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
540 // Keep track of whether the last number was a hexadecimal escape
541 bool LastWasHex = false;
543 // Do not include the last character, which we know is null
544 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
545 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
547 // Print it out literally if it is a printable character. The only thing
548 // to be careful about is when the last letter output was a hex escape
549 // code, in which case we have to be careful not to print out hex digits
550 // explicitly (the C compiler thinks it is a continuation of the previous
551 // character, sheesh...)
553 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
555 if (C == '"' || C == '\\')
562 case '\n': Out << "\\n"; break;
563 case '\t': Out << "\\t"; break;
564 case '\r': Out << "\\r"; break;
565 case '\v': Out << "\\v"; break;
566 case '\a': Out << "\\a"; break;
567 case '\"': Out << "\\\""; break;
568 case '\'': Out << "\\\'"; break;
571 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
572 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
581 if (CPA->getNumOperands()) {
583 printConstant(cast<Constant>(CPA->getOperand(0)));
584 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
586 printConstant(cast<Constant>(CPA->getOperand(i)));
593 void CWriter::printConstantVector(ConstantVector *CP) {
595 if (CP->getNumOperands()) {
597 printConstant(cast<Constant>(CP->getOperand(0)));
598 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
600 printConstant(cast<Constant>(CP->getOperand(i)));
606 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
607 // textually as a double (rather than as a reference to a stack-allocated
608 // variable). We decide this by converting CFP to a string and back into a
609 // double, and then checking whether the conversion results in a bit-equal
610 // double to the original value of CFP. This depends on us and the target C
611 // compiler agreeing on the conversion process (which is pretty likely since we
612 // only deal in IEEE FP).
614 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
615 // Do long doubles in hex for now.
616 if (CFP->getType()!=Type::FloatTy && CFP->getType()!=Type::DoubleTy)
618 APFloat APF = APFloat(CFP->getValueAPF()); // copy
619 if (CFP->getType()==Type::FloatTy)
620 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
621 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
623 sprintf(Buffer, "%a", APF.convertToDouble());
624 if (!strncmp(Buffer, "0x", 2) ||
625 !strncmp(Buffer, "-0x", 3) ||
626 !strncmp(Buffer, "+0x", 3))
627 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
630 std::string StrVal = ftostr(APF);
632 while (StrVal[0] == ' ')
633 StrVal.erase(StrVal.begin());
635 // Check to make sure that the stringized number is not some string like "Inf"
636 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
637 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
638 ((StrVal[0] == '-' || StrVal[0] == '+') &&
639 (StrVal[1] >= '0' && StrVal[1] <= '9')))
640 // Reparse stringized version!
641 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
646 /// Print out the casting for a cast operation. This does the double casting
647 /// necessary for conversion to the destination type, if necessary.
648 /// @brief Print a cast
649 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
650 // Print the destination type cast
652 case Instruction::UIToFP:
653 case Instruction::SIToFP:
654 case Instruction::IntToPtr:
655 case Instruction::Trunc:
656 case Instruction::BitCast:
657 case Instruction::FPExt:
658 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
660 printType(Out, DstTy);
663 case Instruction::ZExt:
664 case Instruction::PtrToInt:
665 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
667 printSimpleType(Out, DstTy, false);
670 case Instruction::SExt:
671 case Instruction::FPToSI: // For these, make sure we get a signed dest
673 printSimpleType(Out, DstTy, true);
677 assert(0 && "Invalid cast opcode");
680 // Print the source type cast
682 case Instruction::UIToFP:
683 case Instruction::ZExt:
685 printSimpleType(Out, SrcTy, false);
688 case Instruction::SIToFP:
689 case Instruction::SExt:
691 printSimpleType(Out, SrcTy, true);
694 case Instruction::IntToPtr:
695 case Instruction::PtrToInt:
696 // Avoid "cast to pointer from integer of different size" warnings
697 Out << "(unsigned long)";
699 case Instruction::Trunc:
700 case Instruction::BitCast:
701 case Instruction::FPExt:
702 case Instruction::FPTrunc:
703 case Instruction::FPToSI:
704 case Instruction::FPToUI:
705 break; // These don't need a source cast.
707 assert(0 && "Invalid cast opcode");
712 // printConstant - The LLVM Constant to C Constant converter.
713 void CWriter::printConstant(Constant *CPV) {
714 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
715 switch (CE->getOpcode()) {
716 case Instruction::Trunc:
717 case Instruction::ZExt:
718 case Instruction::SExt:
719 case Instruction::FPTrunc:
720 case Instruction::FPExt:
721 case Instruction::UIToFP:
722 case Instruction::SIToFP:
723 case Instruction::FPToUI:
724 case Instruction::FPToSI:
725 case Instruction::PtrToInt:
726 case Instruction::IntToPtr:
727 case Instruction::BitCast:
729 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
730 if (CE->getOpcode() == Instruction::SExt &&
731 CE->getOperand(0)->getType() == Type::Int1Ty) {
732 // Make sure we really sext from bool here by subtracting from 0
735 printConstant(CE->getOperand(0));
736 if (CE->getType() == Type::Int1Ty &&
737 (CE->getOpcode() == Instruction::Trunc ||
738 CE->getOpcode() == Instruction::FPToUI ||
739 CE->getOpcode() == Instruction::FPToSI ||
740 CE->getOpcode() == Instruction::PtrToInt)) {
741 // Make sure we really truncate to bool here by anding with 1
747 case Instruction::GetElementPtr:
749 printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
753 case Instruction::Select:
755 printConstant(CE->getOperand(0));
757 printConstant(CE->getOperand(1));
759 printConstant(CE->getOperand(2));
762 case Instruction::Add:
763 case Instruction::Sub:
764 case Instruction::Mul:
765 case Instruction::SDiv:
766 case Instruction::UDiv:
767 case Instruction::FDiv:
768 case Instruction::URem:
769 case Instruction::SRem:
770 case Instruction::FRem:
771 case Instruction::And:
772 case Instruction::Or:
773 case Instruction::Xor:
774 case Instruction::ICmp:
775 case Instruction::Shl:
776 case Instruction::LShr:
777 case Instruction::AShr:
780 bool NeedsClosingParens = printConstExprCast(CE);
781 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
782 switch (CE->getOpcode()) {
783 case Instruction::Add: Out << " + "; break;
784 case Instruction::Sub: Out << " - "; break;
785 case Instruction::Mul: Out << " * "; break;
786 case Instruction::URem:
787 case Instruction::SRem:
788 case Instruction::FRem: Out << " % "; break;
789 case Instruction::UDiv:
790 case Instruction::SDiv:
791 case Instruction::FDiv: Out << " / "; break;
792 case Instruction::And: Out << " & "; break;
793 case Instruction::Or: Out << " | "; break;
794 case Instruction::Xor: Out << " ^ "; break;
795 case Instruction::Shl: Out << " << "; break;
796 case Instruction::LShr:
797 case Instruction::AShr: Out << " >> "; break;
798 case Instruction::ICmp:
799 switch (CE->getPredicate()) {
800 case ICmpInst::ICMP_EQ: Out << " == "; break;
801 case ICmpInst::ICMP_NE: Out << " != "; break;
802 case ICmpInst::ICMP_SLT:
803 case ICmpInst::ICMP_ULT: Out << " < "; break;
804 case ICmpInst::ICMP_SLE:
805 case ICmpInst::ICMP_ULE: Out << " <= "; break;
806 case ICmpInst::ICMP_SGT:
807 case ICmpInst::ICMP_UGT: Out << " > "; break;
808 case ICmpInst::ICMP_SGE:
809 case ICmpInst::ICMP_UGE: Out << " >= "; break;
810 default: assert(0 && "Illegal ICmp predicate");
813 default: assert(0 && "Illegal opcode here!");
815 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
816 if (NeedsClosingParens)
821 case Instruction::FCmp: {
823 bool NeedsClosingParens = printConstExprCast(CE);
824 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
826 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
830 switch (CE->getPredicate()) {
831 default: assert(0 && "Illegal FCmp predicate");
832 case FCmpInst::FCMP_ORD: op = "ord"; break;
833 case FCmpInst::FCMP_UNO: op = "uno"; break;
834 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
835 case FCmpInst::FCMP_UNE: op = "une"; break;
836 case FCmpInst::FCMP_ULT: op = "ult"; break;
837 case FCmpInst::FCMP_ULE: op = "ule"; break;
838 case FCmpInst::FCMP_UGT: op = "ugt"; break;
839 case FCmpInst::FCMP_UGE: op = "uge"; break;
840 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
841 case FCmpInst::FCMP_ONE: op = "one"; break;
842 case FCmpInst::FCMP_OLT: op = "olt"; break;
843 case FCmpInst::FCMP_OLE: op = "ole"; break;
844 case FCmpInst::FCMP_OGT: op = "ogt"; break;
845 case FCmpInst::FCMP_OGE: op = "oge"; break;
847 Out << "llvm_fcmp_" << op << "(";
848 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
850 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
853 if (NeedsClosingParens)
859 cerr << "CWriter Error: Unhandled constant expression: "
863 } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
865 printType(Out, CPV->getType()); // sign doesn't matter
866 Out << ")/*UNDEF*/0)";
870 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
871 const Type* Ty = CI->getType();
872 if (Ty == Type::Int1Ty)
873 Out << (CI->getZExtValue() ? '1' : '0') ;
876 printSimpleType(Out, Ty, false) << ')';
877 if (CI->isMinValue(true))
878 Out << CI->getZExtValue() << 'u';
880 Out << CI->getSExtValue();
881 if (Ty->getPrimitiveSizeInBits() > 32)
888 switch (CPV->getType()->getTypeID()) {
889 case Type::FloatTyID:
890 case Type::DoubleTyID:
891 case Type::X86_FP80TyID:
892 case Type::PPC_FP128TyID:
893 case Type::FP128TyID: {
894 ConstantFP *FPC = cast<ConstantFP>(CPV);
895 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
896 if (I != FPConstantMap.end()) {
897 // Because of FP precision problems we must load from a stack allocated
898 // value that holds the value in hex.
899 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
900 FPC->getType() == Type::DoubleTy ? "double" :
902 << "*)&FPConstant" << I->second << ')';
904 assert(FPC->getType() == Type::FloatTy ||
905 FPC->getType() == Type::DoubleTy);
906 double V = FPC->getType() == Type::FloatTy ?
907 FPC->getValueAPF().convertToFloat() :
908 FPC->getValueAPF().convertToDouble();
912 // FIXME the actual NaN bits should be emitted.
913 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
915 const unsigned long QuietNaN = 0x7ff8UL;
916 //const unsigned long SignalNaN = 0x7ff4UL;
918 // We need to grab the first part of the FP #
921 uint64_t ll = DoubleToBits(V);
922 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
924 std::string Num(&Buffer[0], &Buffer[6]);
925 unsigned long Val = strtoul(Num.c_str(), 0, 16);
927 if (FPC->getType() == Type::FloatTy)
928 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
929 << Buffer << "\") /*nan*/ ";
931 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
932 << Buffer << "\") /*nan*/ ";
933 } else if (IsInf(V)) {
935 if (V < 0) Out << '-';
936 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
940 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
941 // Print out the constant as a floating point number.
943 sprintf(Buffer, "%a", V);
946 Num = ftostr(FPC->getValueAPF());
954 case Type::ArrayTyID:
955 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
956 const ArrayType *AT = cast<ArrayType>(CPV->getType());
958 if (AT->getNumElements()) {
960 Constant *CZ = Constant::getNullValue(AT->getElementType());
962 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
969 printConstantArray(cast<ConstantArray>(CPV));
973 case Type::VectorTyID:
974 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
975 const VectorType *AT = cast<VectorType>(CPV->getType());
977 if (AT->getNumElements()) {
979 Constant *CZ = Constant::getNullValue(AT->getElementType());
981 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
988 printConstantVector(cast<ConstantVector>(CPV));
992 case Type::StructTyID:
993 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
994 const StructType *ST = cast<StructType>(CPV->getType());
996 if (ST->getNumElements()) {
998 printConstant(Constant::getNullValue(ST->getElementType(0)));
999 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1001 printConstant(Constant::getNullValue(ST->getElementType(i)));
1007 if (CPV->getNumOperands()) {
1009 printConstant(cast<Constant>(CPV->getOperand(0)));
1010 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1012 printConstant(cast<Constant>(CPV->getOperand(i)));
1019 case Type::PointerTyID:
1020 if (isa<ConstantPointerNull>(CPV)) {
1022 printType(Out, CPV->getType()); // sign doesn't matter
1023 Out << ")/*NULL*/0)";
1025 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1031 cerr << "Unknown constant type: " << *CPV << "\n";
1036 // Some constant expressions need to be casted back to the original types
1037 // because their operands were casted to the expected type. This function takes
1038 // care of detecting that case and printing the cast for the ConstantExpr.
1039 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
1040 bool NeedsExplicitCast = false;
1041 const Type *Ty = CE->getOperand(0)->getType();
1042 bool TypeIsSigned = false;
1043 switch (CE->getOpcode()) {
1044 case Instruction::LShr:
1045 case Instruction::URem:
1046 case Instruction::UDiv: NeedsExplicitCast = true; break;
1047 case Instruction::AShr:
1048 case Instruction::SRem:
1049 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1050 case Instruction::SExt:
1052 NeedsExplicitCast = true;
1053 TypeIsSigned = true;
1055 case Instruction::ZExt:
1056 case Instruction::Trunc:
1057 case Instruction::FPTrunc:
1058 case Instruction::FPExt:
1059 case Instruction::UIToFP:
1060 case Instruction::SIToFP:
1061 case Instruction::FPToUI:
1062 case Instruction::FPToSI:
1063 case Instruction::PtrToInt:
1064 case Instruction::IntToPtr:
1065 case Instruction::BitCast:
1067 NeedsExplicitCast = true;
1071 if (NeedsExplicitCast) {
1073 if (Ty->isInteger() && Ty != Type::Int1Ty)
1074 printSimpleType(Out, Ty, TypeIsSigned);
1076 printType(Out, Ty); // not integer, sign doesn't matter
1079 return NeedsExplicitCast;
1082 // Print a constant assuming that it is the operand for a given Opcode. The
1083 // opcodes that care about sign need to cast their operands to the expected
1084 // type before the operation proceeds. This function does the casting.
1085 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1087 // Extract the operand's type, we'll need it.
1088 const Type* OpTy = CPV->getType();
1090 // Indicate whether to do the cast or not.
1091 bool shouldCast = false;
1092 bool typeIsSigned = false;
1094 // Based on the Opcode for which this Constant is being written, determine
1095 // the new type to which the operand should be casted by setting the value
1096 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1100 // for most instructions, it doesn't matter
1102 case Instruction::LShr:
1103 case Instruction::UDiv:
1104 case Instruction::URem:
1107 case Instruction::AShr:
1108 case Instruction::SDiv:
1109 case Instruction::SRem:
1111 typeIsSigned = true;
1115 // Write out the casted constant if we should, otherwise just write the
1119 printSimpleType(Out, OpTy, typeIsSigned);
1127 std::string CWriter::GetValueName(const Value *Operand) {
1130 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1131 std::string VarName;
1133 Name = Operand->getName();
1134 VarName.reserve(Name.capacity());
1136 for (std::string::iterator I = Name.begin(), E = Name.end();
1140 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1141 (ch >= '0' && ch <= '9') || ch == '_'))
1147 Name = "llvm_cbe_" + VarName;
1149 Name = Mang->getValueName(Operand);
1155 void CWriter::writeOperandInternal(Value *Operand) {
1156 if (Instruction *I = dyn_cast<Instruction>(Operand))
1157 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1158 // Should we inline this instruction to build a tree?
1165 Constant* CPV = dyn_cast<Constant>(Operand);
1167 if (CPV && !isa<GlobalValue>(CPV))
1170 Out << GetValueName(Operand);
1173 void CWriter::writeOperandRaw(Value *Operand) {
1174 Constant* CPV = dyn_cast<Constant>(Operand);
1175 if (CPV && !isa<GlobalValue>(CPV)) {
1178 Out << GetValueName(Operand);
1182 void CWriter::writeOperand(Value *Operand) {
1183 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1184 Out << "(&"; // Global variables are referenced as their addresses by llvm
1186 writeOperandInternal(Operand);
1188 if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1192 // Some instructions need to have their result value casted back to the
1193 // original types because their operands were casted to the expected type.
1194 // This function takes care of detecting that case and printing the cast
1195 // for the Instruction.
1196 bool CWriter::writeInstructionCast(const Instruction &I) {
1197 const Type *Ty = I.getOperand(0)->getType();
1198 switch (I.getOpcode()) {
1199 case Instruction::LShr:
1200 case Instruction::URem:
1201 case Instruction::UDiv:
1203 printSimpleType(Out, Ty, false);
1206 case Instruction::AShr:
1207 case Instruction::SRem:
1208 case Instruction::SDiv:
1210 printSimpleType(Out, Ty, true);
1218 // Write the operand with a cast to another type based on the Opcode being used.
1219 // This will be used in cases where an instruction has specific type
1220 // requirements (usually signedness) for its operands.
1221 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1223 // Extract the operand's type, we'll need it.
1224 const Type* OpTy = Operand->getType();
1226 // Indicate whether to do the cast or not.
1227 bool shouldCast = false;
1229 // Indicate whether the cast should be to a signed type or not.
1230 bool castIsSigned = false;
1232 // Based on the Opcode for which this Operand is being written, determine
1233 // the new type to which the operand should be casted by setting the value
1234 // of OpTy. If we change OpTy, also set shouldCast to true.
1237 // for most instructions, it doesn't matter
1239 case Instruction::LShr:
1240 case Instruction::UDiv:
1241 case Instruction::URem: // Cast to unsigned first
1243 castIsSigned = false;
1245 case Instruction::GetElementPtr:
1246 case Instruction::AShr:
1247 case Instruction::SDiv:
1248 case Instruction::SRem: // Cast to signed first
1250 castIsSigned = true;
1254 // Write out the casted operand if we should, otherwise just write the
1258 printSimpleType(Out, OpTy, castIsSigned);
1260 writeOperand(Operand);
1263 writeOperand(Operand);
1266 // Write the operand with a cast to another type based on the icmp predicate
1268 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1269 // This has to do a cast to ensure the operand has the right signedness.
1270 // Also, if the operand is a pointer, we make sure to cast to an integer when
1271 // doing the comparison both for signedness and so that the C compiler doesn't
1272 // optimize things like "p < NULL" to false (p may contain an integer value
1274 bool shouldCast = Cmp.isRelational();
1276 // Write out the casted operand if we should, otherwise just write the
1279 writeOperand(Operand);
1283 // Should this be a signed comparison? If so, convert to signed.
1284 bool castIsSigned = Cmp.isSignedPredicate();
1286 // If the operand was a pointer, convert to a large integer type.
1287 const Type* OpTy = Operand->getType();
1288 if (isa<PointerType>(OpTy))
1289 OpTy = TD->getIntPtrType();
1292 printSimpleType(Out, OpTy, castIsSigned);
1294 writeOperand(Operand);
1298 // generateCompilerSpecificCode - This is where we add conditional compilation
1299 // directives to cater to specific compilers as need be.
1301 static void generateCompilerSpecificCode(std::ostream& Out) {
1302 // Alloca is hard to get, and we don't want to include stdlib.h here.
1303 Out << "/* get a declaration for alloca */\n"
1304 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1305 << "#define alloca(x) __builtin_alloca((x))\n"
1306 << "#define _alloca(x) __builtin_alloca((x))\n"
1307 << "#elif defined(__APPLE__)\n"
1308 << "extern void *__builtin_alloca(unsigned long);\n"
1309 << "#define alloca(x) __builtin_alloca(x)\n"
1310 << "#define longjmp _longjmp\n"
1311 << "#define setjmp _setjmp\n"
1312 << "#elif defined(__sun__)\n"
1313 << "#if defined(__sparcv9)\n"
1314 << "extern void *__builtin_alloca(unsigned long);\n"
1316 << "extern void *__builtin_alloca(unsigned int);\n"
1318 << "#define alloca(x) __builtin_alloca(x)\n"
1319 << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1320 << "#define alloca(x) __builtin_alloca(x)\n"
1321 << "#elif defined(_MSC_VER)\n"
1322 << "#define inline _inline\n"
1323 << "#define alloca(x) _alloca(x)\n"
1325 << "#include <alloca.h>\n"
1328 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1329 // If we aren't being compiled with GCC, just drop these attributes.
1330 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1331 << "#define __attribute__(X)\n"
1334 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1335 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1336 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1337 << "#elif defined(__GNUC__)\n"
1338 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1340 << "#define __EXTERNAL_WEAK__\n"
1343 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1344 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1345 << "#define __ATTRIBUTE_WEAK__\n"
1346 << "#elif defined(__GNUC__)\n"
1347 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1349 << "#define __ATTRIBUTE_WEAK__\n"
1352 // Add hidden visibility support. FIXME: APPLE_CC?
1353 Out << "#if defined(__GNUC__)\n"
1354 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1357 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1358 // From the GCC documentation:
1360 // double __builtin_nan (const char *str)
1362 // This is an implementation of the ISO C99 function nan.
1364 // Since ISO C99 defines this function in terms of strtod, which we do
1365 // not implement, a description of the parsing is in order. The string is
1366 // parsed as by strtol; that is, the base is recognized by leading 0 or
1367 // 0x prefixes. The number parsed is placed in the significand such that
1368 // the least significant bit of the number is at the least significant
1369 // bit of the significand. The number is truncated to fit the significand
1370 // field provided. The significand is forced to be a quiet NaN.
1372 // This function, if given a string literal, is evaluated early enough
1373 // that it is considered a compile-time constant.
1375 // float __builtin_nanf (const char *str)
1377 // Similar to __builtin_nan, except the return type is float.
1379 // double __builtin_inf (void)
1381 // Similar to __builtin_huge_val, except a warning is generated if the
1382 // target floating-point format does not support infinities. This
1383 // function is suitable for implementing the ISO C99 macro INFINITY.
1385 // float __builtin_inff (void)
1387 // Similar to __builtin_inf, except the return type is float.
1388 Out << "#ifdef __GNUC__\n"
1389 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1390 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1391 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1392 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1393 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1394 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1395 << "#define LLVM_PREFETCH(addr,rw,locality) "
1396 "__builtin_prefetch(addr,rw,locality)\n"
1397 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1398 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1399 << "#define LLVM_ASM __asm__\n"
1401 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1402 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1403 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1404 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1405 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1406 << "#define LLVM_INFF 0.0F /* Float */\n"
1407 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1408 << "#define __ATTRIBUTE_CTOR__\n"
1409 << "#define __ATTRIBUTE_DTOR__\n"
1410 << "#define LLVM_ASM(X)\n"
1413 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1414 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1415 << "#define __builtin_stack_restore(X) /* noop */\n"
1418 // Output target-specific code that should be inserted into main.
1419 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1422 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1423 /// the StaticTors set.
1424 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1425 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1426 if (!InitList) return;
1428 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1429 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1430 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1432 if (CS->getOperand(1)->isNullValue())
1433 return; // Found a null terminator, exit printing.
1434 Constant *FP = CS->getOperand(1);
1435 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1437 FP = CE->getOperand(0);
1438 if (Function *F = dyn_cast<Function>(FP))
1439 StaticTors.insert(F);
1443 enum SpecialGlobalClass {
1445 GlobalCtors, GlobalDtors,
1449 /// getGlobalVariableClass - If this is a global that is specially recognized
1450 /// by LLVM, return a code that indicates how we should handle it.
1451 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1452 // If this is a global ctors/dtors list, handle it now.
1453 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1454 if (GV->getName() == "llvm.global_ctors")
1456 else if (GV->getName() == "llvm.global_dtors")
1460 // Otherwise, it it is other metadata, don't print it. This catches things
1461 // like debug information.
1462 if (GV->getSection() == "llvm.metadata")
1469 bool CWriter::doInitialization(Module &M) {
1473 TD = new TargetData(&M);
1474 IL = new IntrinsicLowering(*TD);
1475 IL->AddPrototypes(M);
1477 // Ensure that all structure types have names...
1478 Mang = new Mangler(M);
1479 Mang->markCharUnacceptable('.');
1481 // Keep track of which functions are static ctors/dtors so they can have
1482 // an attribute added to their prototypes.
1483 std::set<Function*> StaticCtors, StaticDtors;
1484 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1486 switch (getGlobalVariableClass(I)) {
1489 FindStaticTors(I, StaticCtors);
1492 FindStaticTors(I, StaticDtors);
1497 // get declaration for alloca
1498 Out << "/* Provide Declarations */\n";
1499 Out << "#include <stdarg.h>\n"; // Varargs support
1500 Out << "#include <setjmp.h>\n"; // Unwind support
1501 generateCompilerSpecificCode(Out);
1503 // Provide a definition for `bool' if not compiling with a C++ compiler.
1505 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1507 << "\n\n/* Support for floating point constants */\n"
1508 << "typedef unsigned long long ConstantDoubleTy;\n"
1509 << "typedef unsigned int ConstantFloatTy;\n"
1510 << "typedef struct { unsigned long long f1; unsigned short f2; "
1511 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1512 // This is used for both kinds of 128-bit long double; meaning differs.
1513 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1514 " ConstantFP128Ty;\n"
1515 << "\n\n/* Global Declarations */\n";
1517 // First output all the declarations for the program, because C requires
1518 // Functions & globals to be declared before they are used.
1521 // Loop over the symbol table, emitting all named constants...
1522 printModuleTypes(M.getTypeSymbolTable());
1524 // Global variable declarations...
1525 if (!M.global_empty()) {
1526 Out << "\n/* External Global Variable Declarations */\n";
1527 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1530 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
1532 else if (I->hasDLLImportLinkage())
1533 Out << "__declspec(dllimport) ";
1535 continue; // Internal Global
1537 // Thread Local Storage
1538 if (I->isThreadLocal())
1541 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1543 if (I->hasExternalWeakLinkage())
1544 Out << " __EXTERNAL_WEAK__";
1549 // Function declarations
1550 Out << "\n/* Function Declarations */\n";
1551 Out << "double fmod(double, double);\n"; // Support for FP rem
1552 Out << "float fmodf(float, float);\n";
1553 Out << "long double fmodl(long double, long double);\n";
1555 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1556 // Don't print declarations for intrinsic functions.
1557 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1558 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1559 if (I->hasExternalWeakLinkage())
1561 printFunctionSignature(I, true);
1562 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1563 Out << " __ATTRIBUTE_WEAK__";
1564 if (I->hasExternalWeakLinkage())
1565 Out << " __EXTERNAL_WEAK__";
1566 if (StaticCtors.count(I))
1567 Out << " __ATTRIBUTE_CTOR__";
1568 if (StaticDtors.count(I))
1569 Out << " __ATTRIBUTE_DTOR__";
1570 if (I->hasHiddenVisibility())
1571 Out << " __HIDDEN__";
1573 if (I->hasName() && I->getName()[0] == 1)
1574 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1580 // Output the global variable declarations
1581 if (!M.global_empty()) {
1582 Out << "\n\n/* Global Variable Declarations */\n";
1583 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1585 if (!I->isDeclaration()) {
1586 // Ignore special globals, such as debug info.
1587 if (getGlobalVariableClass(I))
1590 if (I->hasInternalLinkage())
1595 // Thread Local Storage
1596 if (I->isThreadLocal())
1599 printType(Out, I->getType()->getElementType(), false,
1602 if (I->hasLinkOnceLinkage())
1603 Out << " __attribute__((common))";
1604 else if (I->hasWeakLinkage())
1605 Out << " __ATTRIBUTE_WEAK__";
1606 else if (I->hasExternalWeakLinkage())
1607 Out << " __EXTERNAL_WEAK__";
1608 if (I->hasHiddenVisibility())
1609 Out << " __HIDDEN__";
1614 // Output the global variable definitions and contents...
1615 if (!M.global_empty()) {
1616 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1617 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1619 if (!I->isDeclaration()) {
1620 // Ignore special globals, such as debug info.
1621 if (getGlobalVariableClass(I))
1624 if (I->hasInternalLinkage())
1626 else if (I->hasDLLImportLinkage())
1627 Out << "__declspec(dllimport) ";
1628 else if (I->hasDLLExportLinkage())
1629 Out << "__declspec(dllexport) ";
1631 // Thread Local Storage
1632 if (I->isThreadLocal())
1635 printType(Out, I->getType()->getElementType(), false,
1637 if (I->hasLinkOnceLinkage())
1638 Out << " __attribute__((common))";
1639 else if (I->hasWeakLinkage())
1640 Out << " __ATTRIBUTE_WEAK__";
1642 if (I->hasHiddenVisibility())
1643 Out << " __HIDDEN__";
1645 // If the initializer is not null, emit the initializer. If it is null,
1646 // we try to avoid emitting large amounts of zeros. The problem with
1647 // this, however, occurs when the variable has weak linkage. In this
1648 // case, the assembler will complain about the variable being both weak
1649 // and common, so we disable this optimization.
1650 if (!I->getInitializer()->isNullValue()) {
1652 writeOperand(I->getInitializer());
1653 } else if (I->hasWeakLinkage()) {
1654 // We have to specify an initializer, but it doesn't have to be
1655 // complete. If the value is an aggregate, print out { 0 }, and let
1656 // the compiler figure out the rest of the zeros.
1658 if (isa<StructType>(I->getInitializer()->getType()) ||
1659 isa<ArrayType>(I->getInitializer()->getType()) ||
1660 isa<VectorType>(I->getInitializer()->getType())) {
1663 // Just print it out normally.
1664 writeOperand(I->getInitializer());
1672 Out << "\n\n/* Function Bodies */\n";
1674 // Emit some helper functions for dealing with FCMP instruction's
1676 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1677 Out << "return X == X && Y == Y; }\n";
1678 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1679 Out << "return X != X || Y != Y; }\n";
1680 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1681 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1682 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1683 Out << "return X != Y; }\n";
1684 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1685 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1686 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1687 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1688 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1689 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1690 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1691 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1692 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1693 Out << "return X == Y ; }\n";
1694 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1695 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1696 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1697 Out << "return X < Y ; }\n";
1698 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1699 Out << "return X > Y ; }\n";
1700 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1701 Out << "return X <= Y ; }\n";
1702 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1703 Out << "return X >= Y ; }\n";
1708 /// Output all floating point constants that cannot be printed accurately...
1709 void CWriter::printFloatingPointConstants(Function &F) {
1710 // Scan the module for floating point constants. If any FP constant is used
1711 // in the function, we want to redirect it here so that we do not depend on
1712 // the precision of the printed form, unless the printed form preserves
1715 static unsigned FPCounter = 0;
1716 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1718 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1719 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1720 !FPConstantMap.count(FPC)) {
1721 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1723 if (FPC->getType() == Type::DoubleTy) {
1724 double Val = FPC->getValueAPF().convertToDouble();
1725 uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
1726 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1727 << " = 0x" << std::hex << i << std::dec
1728 << "ULL; /* " << Val << " */\n";
1729 } else if (FPC->getType() == Type::FloatTy) {
1730 float Val = FPC->getValueAPF().convertToFloat();
1731 uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
1733 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1734 << " = 0x" << std::hex << i << std::dec
1735 << "U; /* " << Val << " */\n";
1736 } else if (FPC->getType() == Type::X86_FP80Ty) {
1737 // api needed to prevent premature destruction
1738 APInt api = FPC->getValueAPF().convertToAPInt();
1739 const uint64_t *p = api.getRawData();
1740 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
1741 << " = { 0x" << std::hex
1742 << ((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16)
1743 << ", 0x" << (uint16_t)(p[0] >> 48) << ",0,0,0"
1744 << "}; /* Long double constant */\n" << std::dec;
1745 } else if (FPC->getType() == Type::PPC_FP128Ty) {
1746 APInt api = FPC->getValueAPF().convertToAPInt();
1747 const uint64_t *p = api.getRawData();
1748 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
1749 << " = { 0x" << std::hex
1750 << p[0] << ", 0x" << p[1]
1751 << "}; /* Long double constant */\n" << std::dec;
1754 assert(0 && "Unknown float type!");
1761 /// printSymbolTable - Run through symbol table looking for type names. If a
1762 /// type name is found, emit its declaration...
1764 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1765 Out << "/* Helper union for bitcasts */\n";
1766 Out << "typedef union {\n";
1767 Out << " unsigned int Int32;\n";
1768 Out << " unsigned long long Int64;\n";
1769 Out << " float Float;\n";
1770 Out << " double Double;\n";
1771 Out << "} llvmBitCastUnion;\n";
1773 // We are only interested in the type plane of the symbol table.
1774 TypeSymbolTable::const_iterator I = TST.begin();
1775 TypeSymbolTable::const_iterator End = TST.end();
1777 // If there are no type names, exit early.
1778 if (I == End) return;
1780 // Print out forward declarations for structure types before anything else!
1781 Out << "/* Structure forward decls */\n";
1782 for (; I != End; ++I) {
1783 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1784 Out << Name << ";\n";
1785 TypeNames.insert(std::make_pair(I->second, Name));
1790 // Now we can print out typedefs. Above, we guaranteed that this can only be
1791 // for struct or opaque types.
1792 Out << "/* Typedefs */\n";
1793 for (I = TST.begin(); I != End; ++I) {
1794 std::string Name = "l_" + Mang->makeNameProper(I->first);
1796 printType(Out, I->second, false, Name);
1802 // Keep track of which structures have been printed so far...
1803 std::set<const StructType *> StructPrinted;
1805 // Loop over all structures then push them into the stack so they are
1806 // printed in the correct order.
1808 Out << "/* Structure contents */\n";
1809 for (I = TST.begin(); I != End; ++I)
1810 if (const StructType *STy = dyn_cast<StructType>(I->second))
1811 // Only print out used types!
1812 printContainedStructs(STy, StructPrinted);
1815 // Push the struct onto the stack and recursively push all structs
1816 // this one depends on.
1818 // TODO: Make this work properly with vector types
1820 void CWriter::printContainedStructs(const Type *Ty,
1821 std::set<const StructType*> &StructPrinted){
1822 // Don't walk through pointers.
1823 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1825 // Print all contained types first.
1826 for (Type::subtype_iterator I = Ty->subtype_begin(),
1827 E = Ty->subtype_end(); I != E; ++I)
1828 printContainedStructs(*I, StructPrinted);
1830 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1831 // Check to see if we have already printed this struct.
1832 if (StructPrinted.insert(STy).second) {
1833 // Print structure type out.
1834 std::string Name = TypeNames[STy];
1835 printType(Out, STy, false, Name, true);
1841 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1842 /// isStructReturn - Should this function actually return a struct by-value?
1843 bool isStructReturn = F->isStructReturn();
1845 if (F->hasInternalLinkage()) Out << "static ";
1846 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1847 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1848 switch (F->getCallingConv()) {
1849 case CallingConv::X86_StdCall:
1850 Out << "__stdcall ";
1852 case CallingConv::X86_FastCall:
1853 Out << "__fastcall ";
1857 // Loop over the arguments, printing them...
1858 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1859 const ParamAttrsList *PAL = F->getParamAttrs();
1861 std::stringstream FunctionInnards;
1863 // Print out the name...
1864 FunctionInnards << GetValueName(F) << '(';
1866 bool PrintedArg = false;
1867 if (!F->isDeclaration()) {
1868 if (!F->arg_empty()) {
1869 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1872 // If this is a struct-return function, don't print the hidden
1873 // struct-return argument.
1874 if (isStructReturn) {
1875 assert(I != E && "Invalid struct return function!");
1880 std::string ArgName;
1881 for (; I != E; ++I) {
1882 if (PrintedArg) FunctionInnards << ", ";
1883 if (I->hasName() || !Prototype)
1884 ArgName = GetValueName(I);
1887 const Type *ArgTy = I->getType();
1888 printType(FunctionInnards, ArgTy,
1889 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt),
1896 // Loop over the arguments, printing them.
1897 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1899 // If this is a struct-return function, don't print the hidden
1900 // struct-return argument.
1901 if (isStructReturn) {
1902 assert(I != E && "Invalid struct return function!");
1907 for (; I != E; ++I) {
1908 if (PrintedArg) FunctionInnards << ", ";
1909 printType(FunctionInnards, *I,
1910 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
1916 // Finish printing arguments... if this is a vararg function, print the ...,
1917 // unless there are no known types, in which case, we just emit ().
1919 if (FT->isVarArg() && PrintedArg) {
1920 if (PrintedArg) FunctionInnards << ", ";
1921 FunctionInnards << "..."; // Output varargs portion of signature!
1922 } else if (!FT->isVarArg() && !PrintedArg) {
1923 FunctionInnards << "void"; // ret() -> ret(void) in C.
1925 FunctionInnards << ')';
1927 // Get the return tpe for the function.
1929 if (!isStructReturn)
1930 RetTy = F->getReturnType();
1932 // If this is a struct-return function, print the struct-return type.
1933 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1936 // Print out the return type and the signature built above.
1937 printType(Out, RetTy,
1938 /*isSigned=*/ PAL && PAL->paramHasAttr(0, ParamAttr::SExt),
1939 FunctionInnards.str());
1942 static inline bool isFPIntBitCast(const Instruction &I) {
1943 if (!isa<BitCastInst>(I))
1945 const Type *SrcTy = I.getOperand(0)->getType();
1946 const Type *DstTy = I.getType();
1947 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
1948 (DstTy->isFloatingPoint() && SrcTy->isInteger());
1951 void CWriter::printFunction(Function &F) {
1952 /// isStructReturn - Should this function actually return a struct by-value?
1953 bool isStructReturn = F.isStructReturn();
1955 printFunctionSignature(&F, false);
1958 // If this is a struct return function, handle the result with magic.
1959 if (isStructReturn) {
1960 const Type *StructTy =
1961 cast<PointerType>(F.arg_begin()->getType())->getElementType();
1963 printType(Out, StructTy, false, "StructReturn");
1964 Out << "; /* Struct return temporary */\n";
1967 printType(Out, F.arg_begin()->getType(), false,
1968 GetValueName(F.arg_begin()));
1969 Out << " = &StructReturn;\n";
1972 bool PrintedVar = false;
1974 // print local variable information for the function
1975 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
1976 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1978 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
1979 Out << "; /* Address-exposed local */\n";
1981 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1983 printType(Out, I->getType(), false, GetValueName(&*I));
1986 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
1988 printType(Out, I->getType(), false,
1989 GetValueName(&*I)+"__PHI_TEMPORARY");
1994 // We need a temporary for the BitCast to use so it can pluck a value out
1995 // of a union to do the BitCast. This is separate from the need for a
1996 // variable to hold the result of the BitCast.
1997 if (isFPIntBitCast(*I)) {
1998 Out << " llvmBitCastUnion " << GetValueName(&*I)
1999 << "__BITCAST_TEMPORARY;\n";
2007 if (F.hasExternalLinkage() && F.getName() == "main")
2008 Out << " CODE_FOR_MAIN();\n";
2010 // print the basic blocks
2011 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2012 if (Loop *L = LI->getLoopFor(BB)) {
2013 if (L->getHeader() == BB && L->getParentLoop() == 0)
2016 printBasicBlock(BB);
2023 void CWriter::printLoop(Loop *L) {
2024 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2025 << "' to make GCC happy */\n";
2026 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2027 BasicBlock *BB = L->getBlocks()[i];
2028 Loop *BBLoop = LI->getLoopFor(BB);
2030 printBasicBlock(BB);
2031 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2034 Out << " } while (1); /* end of syntactic loop '"
2035 << L->getHeader()->getName() << "' */\n";
2038 void CWriter::printBasicBlock(BasicBlock *BB) {
2040 // Don't print the label for the basic block if there are no uses, or if
2041 // the only terminator use is the predecessor basic block's terminator.
2042 // We have to scan the use list because PHI nodes use basic blocks too but
2043 // do not require a label to be generated.
2045 bool NeedsLabel = false;
2046 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2047 if (isGotoCodeNecessary(*PI, BB)) {
2052 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2054 // Output all of the instructions in the basic block...
2055 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2057 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2058 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2067 // Don't emit prefix or suffix for the terminator...
2068 visit(*BB->getTerminator());
2072 // Specific Instruction type classes... note that all of the casts are
2073 // necessary because we use the instruction classes as opaque types...
2075 void CWriter::visitReturnInst(ReturnInst &I) {
2076 // If this is a struct return function, return the temporary struct.
2077 bool isStructReturn = I.getParent()->getParent()->isStructReturn();
2079 if (isStructReturn) {
2080 Out << " return StructReturn;\n";
2084 // Don't output a void return if this is the last basic block in the function
2085 if (I.getNumOperands() == 0 &&
2086 &*--I.getParent()->getParent()->end() == I.getParent() &&
2087 !I.getParent()->size() == 1) {
2092 if (I.getNumOperands()) {
2094 writeOperand(I.getOperand(0));
2099 void CWriter::visitSwitchInst(SwitchInst &SI) {
2102 writeOperand(SI.getOperand(0));
2103 Out << ") {\n default:\n";
2104 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2105 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2107 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2109 writeOperand(SI.getOperand(i));
2111 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2112 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2113 printBranchToBlock(SI.getParent(), Succ, 2);
2114 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2120 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2121 Out << " /*UNREACHABLE*/;\n";
2124 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2125 /// FIXME: This should be reenabled, but loop reordering safe!!
2128 if (next(Function::iterator(From)) != Function::iterator(To))
2129 return true; // Not the direct successor, we need a goto.
2131 //isa<SwitchInst>(From->getTerminator())
2133 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2138 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2139 BasicBlock *Successor,
2141 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2142 PHINode *PN = cast<PHINode>(I);
2143 // Now we have to do the printing.
2144 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2145 if (!isa<UndefValue>(IV)) {
2146 Out << std::string(Indent, ' ');
2147 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2149 Out << "; /* for PHI node */\n";
2154 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2156 if (isGotoCodeNecessary(CurBB, Succ)) {
2157 Out << std::string(Indent, ' ') << " goto ";
2163 // Branch instruction printing - Avoid printing out a branch to a basic block
2164 // that immediately succeeds the current one.
2166 void CWriter::visitBranchInst(BranchInst &I) {
2168 if (I.isConditional()) {
2169 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2171 writeOperand(I.getCondition());
2174 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2175 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2177 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2178 Out << " } else {\n";
2179 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2180 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2183 // First goto not necessary, assume second one is...
2185 writeOperand(I.getCondition());
2188 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2189 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2194 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2195 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2200 // PHI nodes get copied into temporary values at the end of predecessor basic
2201 // blocks. We now need to copy these temporary values into the REAL value for
2203 void CWriter::visitPHINode(PHINode &I) {
2205 Out << "__PHI_TEMPORARY";
2209 void CWriter::visitBinaryOperator(Instruction &I) {
2210 // binary instructions, shift instructions, setCond instructions.
2211 assert(!isa<PointerType>(I.getType()));
2213 // We must cast the results of binary operations which might be promoted.
2214 bool needsCast = false;
2215 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2216 || (I.getType() == Type::FloatTy)) {
2219 printType(Out, I.getType(), false);
2223 // If this is a negation operation, print it out as such. For FP, we don't
2224 // want to print "-0.0 - X".
2225 if (BinaryOperator::isNeg(&I)) {
2227 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2229 } else if (I.getOpcode() == Instruction::FRem) {
2230 // Output a call to fmod/fmodf instead of emitting a%b
2231 if (I.getType() == Type::FloatTy)
2233 else if (I.getType() == Type::DoubleTy)
2235 else // all 3 flavors of long double
2237 writeOperand(I.getOperand(0));
2239 writeOperand(I.getOperand(1));
2243 // Write out the cast of the instruction's value back to the proper type
2245 bool NeedsClosingParens = writeInstructionCast(I);
2247 // Certain instructions require the operand to be forced to a specific type
2248 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2249 // below for operand 1
2250 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2252 switch (I.getOpcode()) {
2253 case Instruction::Add: Out << " + "; break;
2254 case Instruction::Sub: Out << " - "; break;
2255 case Instruction::Mul: Out << " * "; break;
2256 case Instruction::URem:
2257 case Instruction::SRem:
2258 case Instruction::FRem: Out << " % "; break;
2259 case Instruction::UDiv:
2260 case Instruction::SDiv:
2261 case Instruction::FDiv: Out << " / "; break;
2262 case Instruction::And: Out << " & "; break;
2263 case Instruction::Or: Out << " | "; break;
2264 case Instruction::Xor: Out << " ^ "; break;
2265 case Instruction::Shl : Out << " << "; break;
2266 case Instruction::LShr:
2267 case Instruction::AShr: Out << " >> "; break;
2268 default: cerr << "Invalid operator type!" << I; abort();
2271 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2272 if (NeedsClosingParens)
2281 void CWriter::visitICmpInst(ICmpInst &I) {
2282 // We must cast the results of icmp which might be promoted.
2283 bool needsCast = false;
2285 // Write out the cast of the instruction's value back to the proper type
2287 bool NeedsClosingParens = writeInstructionCast(I);
2289 // Certain icmp predicate require the operand to be forced to a specific type
2290 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2291 // below for operand 1
2292 writeOperandWithCast(I.getOperand(0), I);
2294 switch (I.getPredicate()) {
2295 case ICmpInst::ICMP_EQ: Out << " == "; break;
2296 case ICmpInst::ICMP_NE: Out << " != "; break;
2297 case ICmpInst::ICMP_ULE:
2298 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2299 case ICmpInst::ICMP_UGE:
2300 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2301 case ICmpInst::ICMP_ULT:
2302 case ICmpInst::ICMP_SLT: Out << " < "; break;
2303 case ICmpInst::ICMP_UGT:
2304 case ICmpInst::ICMP_SGT: Out << " > "; break;
2305 default: cerr << "Invalid icmp predicate!" << I; abort();
2308 writeOperandWithCast(I.getOperand(1), I);
2309 if (NeedsClosingParens)
2317 void CWriter::visitFCmpInst(FCmpInst &I) {
2318 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2322 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2328 switch (I.getPredicate()) {
2329 default: assert(0 && "Illegal FCmp predicate");
2330 case FCmpInst::FCMP_ORD: op = "ord"; break;
2331 case FCmpInst::FCMP_UNO: op = "uno"; break;
2332 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2333 case FCmpInst::FCMP_UNE: op = "une"; break;
2334 case FCmpInst::FCMP_ULT: op = "ult"; break;
2335 case FCmpInst::FCMP_ULE: op = "ule"; break;
2336 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2337 case FCmpInst::FCMP_UGE: op = "uge"; break;
2338 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2339 case FCmpInst::FCMP_ONE: op = "one"; break;
2340 case FCmpInst::FCMP_OLT: op = "olt"; break;
2341 case FCmpInst::FCMP_OLE: op = "ole"; break;
2342 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2343 case FCmpInst::FCMP_OGE: op = "oge"; break;
2346 Out << "llvm_fcmp_" << op << "(";
2347 // Write the first operand
2348 writeOperand(I.getOperand(0));
2350 // Write the second operand
2351 writeOperand(I.getOperand(1));
2355 static const char * getFloatBitCastField(const Type *Ty) {
2356 switch (Ty->getTypeID()) {
2357 default: assert(0 && "Invalid Type");
2358 case Type::FloatTyID: return "Float";
2359 case Type::DoubleTyID: return "Double";
2360 case Type::IntegerTyID: {
2361 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2370 void CWriter::visitCastInst(CastInst &I) {
2371 const Type *DstTy = I.getType();
2372 const Type *SrcTy = I.getOperand(0)->getType();
2374 if (isFPIntBitCast(I)) {
2375 // These int<->float and long<->double casts need to be handled specially
2376 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2377 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2378 writeOperand(I.getOperand(0));
2379 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2380 << getFloatBitCastField(I.getType());
2382 printCast(I.getOpcode(), SrcTy, DstTy);
2383 if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
2384 // Make sure we really get a sext from bool by subtracing the bool from 0
2387 writeOperand(I.getOperand(0));
2388 if (DstTy == Type::Int1Ty &&
2389 (I.getOpcode() == Instruction::Trunc ||
2390 I.getOpcode() == Instruction::FPToUI ||
2391 I.getOpcode() == Instruction::FPToSI ||
2392 I.getOpcode() == Instruction::PtrToInt)) {
2393 // Make sure we really get a trunc to bool by anding the operand with 1
2400 void CWriter::visitSelectInst(SelectInst &I) {
2402 writeOperand(I.getCondition());
2404 writeOperand(I.getTrueValue());
2406 writeOperand(I.getFalseValue());
2411 void CWriter::lowerIntrinsics(Function &F) {
2412 // This is used to keep track of intrinsics that get generated to a lowered
2413 // function. We must generate the prototypes before the function body which
2414 // will only be expanded on first use (by the loop below).
2415 std::vector<Function*> prototypesToGen;
2417 // Examine all the instructions in this function to find the intrinsics that
2418 // need to be lowered.
2419 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2420 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2421 if (CallInst *CI = dyn_cast<CallInst>(I++))
2422 if (Function *F = CI->getCalledFunction())
2423 switch (F->getIntrinsicID()) {
2424 case Intrinsic::not_intrinsic:
2425 case Intrinsic::vastart:
2426 case Intrinsic::vacopy:
2427 case Intrinsic::vaend:
2428 case Intrinsic::returnaddress:
2429 case Intrinsic::frameaddress:
2430 case Intrinsic::setjmp:
2431 case Intrinsic::longjmp:
2432 case Intrinsic::prefetch:
2433 case Intrinsic::dbg_stoppoint:
2434 case Intrinsic::powi:
2435 // We directly implement these intrinsics
2438 // If this is an intrinsic that directly corresponds to a GCC
2439 // builtin, we handle it.
2440 const char *BuiltinName = "";
2441 #define GET_GCC_BUILTIN_NAME
2442 #include "llvm/Intrinsics.gen"
2443 #undef GET_GCC_BUILTIN_NAME
2444 // If we handle it, don't lower it.
2445 if (BuiltinName[0]) break;
2447 // All other intrinsic calls we must lower.
2448 Instruction *Before = 0;
2449 if (CI != &BB->front())
2450 Before = prior(BasicBlock::iterator(CI));
2452 IL->LowerIntrinsicCall(CI);
2453 if (Before) { // Move iterator to instruction after call
2458 // If the intrinsic got lowered to another call, and that call has
2459 // a definition then we need to make sure its prototype is emitted
2460 // before any calls to it.
2461 if (CallInst *Call = dyn_cast<CallInst>(I))
2462 if (Function *NewF = Call->getCalledFunction())
2463 if (!NewF->isDeclaration())
2464 prototypesToGen.push_back(NewF);
2469 // We may have collected some prototypes to emit in the loop above.
2470 // Emit them now, before the function that uses them is emitted. But,
2471 // be careful not to emit them twice.
2472 std::vector<Function*>::iterator I = prototypesToGen.begin();
2473 std::vector<Function*>::iterator E = prototypesToGen.end();
2474 for ( ; I != E; ++I) {
2475 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2477 printFunctionSignature(*I, true);
2484 void CWriter::visitCallInst(CallInst &I) {
2485 //check if we have inline asm
2486 if (isInlineAsm(I)) {
2491 bool WroteCallee = false;
2493 // Handle intrinsic function calls first...
2494 if (Function *F = I.getCalledFunction())
2495 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2498 // If this is an intrinsic that directly corresponds to a GCC
2499 // builtin, we emit it here.
2500 const char *BuiltinName = "";
2501 #define GET_GCC_BUILTIN_NAME
2502 #include "llvm/Intrinsics.gen"
2503 #undef GET_GCC_BUILTIN_NAME
2504 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2510 case Intrinsic::vastart:
2513 Out << "va_start(*(va_list*)";
2514 writeOperand(I.getOperand(1));
2516 // Output the last argument to the enclosing function...
2517 if (I.getParent()->getParent()->arg_empty()) {
2518 cerr << "The C backend does not currently support zero "
2519 << "argument varargs functions, such as '"
2520 << I.getParent()->getParent()->getName() << "'!\n";
2523 writeOperand(--I.getParent()->getParent()->arg_end());
2526 case Intrinsic::vaend:
2527 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2528 Out << "0; va_end(*(va_list*)";
2529 writeOperand(I.getOperand(1));
2532 Out << "va_end(*(va_list*)0)";
2535 case Intrinsic::vacopy:
2537 Out << "va_copy(*(va_list*)";
2538 writeOperand(I.getOperand(1));
2539 Out << ", *(va_list*)";
2540 writeOperand(I.getOperand(2));
2543 case Intrinsic::returnaddress:
2544 Out << "__builtin_return_address(";
2545 writeOperand(I.getOperand(1));
2548 case Intrinsic::frameaddress:
2549 Out << "__builtin_frame_address(";
2550 writeOperand(I.getOperand(1));
2553 case Intrinsic::powi:
2554 Out << "__builtin_powi(";
2555 writeOperand(I.getOperand(1));
2557 writeOperand(I.getOperand(2));
2560 case Intrinsic::setjmp:
2561 Out << "setjmp(*(jmp_buf*)";
2562 writeOperand(I.getOperand(1));
2565 case Intrinsic::longjmp:
2566 Out << "longjmp(*(jmp_buf*)";
2567 writeOperand(I.getOperand(1));
2569 writeOperand(I.getOperand(2));
2572 case Intrinsic::prefetch:
2573 Out << "LLVM_PREFETCH((const void *)";
2574 writeOperand(I.getOperand(1));
2576 writeOperand(I.getOperand(2));
2578 writeOperand(I.getOperand(3));
2581 case Intrinsic::stacksave:
2582 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
2583 // to work around GCC bugs (see PR1809).
2584 Out << "0; *((void**)&" << GetValueName(&I)
2585 << ") = __builtin_stack_save()";
2587 case Intrinsic::dbg_stoppoint: {
2588 // If we use writeOperand directly we get a "u" suffix which is rejected
2590 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2594 << " \"" << SPI.getDirectory()
2595 << SPI.getFileName() << "\"\n";
2601 Value *Callee = I.getCalledValue();
2603 const PointerType *PTy = cast<PointerType>(Callee->getType());
2604 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2606 // If this is a call to a struct-return function, assign to the first
2607 // parameter instead of passing it to the call.
2608 const ParamAttrsList *PAL = I.getParamAttrs();
2609 bool isStructRet = I.isStructReturn();
2612 writeOperand(I.getOperand(1));
2616 if (I.isTailCall()) Out << " /*tail*/ ";
2619 // If this is an indirect call to a struct return function, we need to cast
2621 bool NeedsCast = isStructRet && !isa<Function>(Callee);
2623 // GCC is a real PITA. It does not permit codegening casts of functions to
2624 // function pointers if they are in a call (it generates a trap instruction
2625 // instead!). We work around this by inserting a cast to void* in between
2626 // the function and the function pointer cast. Unfortunately, we can't just
2627 // form the constant expression here, because the folder will immediately
2630 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2631 // that void* and function pointers have the same size. :( To deal with this
2632 // in the common case, we handle casts where the number of arguments passed
2635 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2637 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2643 // Ok, just cast the pointer type.
2646 printType(Out, I.getCalledValue()->getType());
2648 printStructReturnPointerFunctionType(Out, PAL,
2649 cast<PointerType>(I.getCalledValue()->getType()));
2652 writeOperand(Callee);
2653 if (NeedsCast) Out << ')';
2658 unsigned NumDeclaredParams = FTy->getNumParams();
2660 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2662 if (isStructRet) { // Skip struct return argument.
2667 bool PrintedArg = false;
2669 for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
2670 if (PrintedArg) Out << ", ";
2671 if (ArgNo < NumDeclaredParams &&
2672 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2674 printType(Out, FTy->getParamType(ArgNo),
2675 /*isSigned=*/PAL && PAL->paramHasAttr(Idx, ParamAttr::SExt));
2685 //This converts the llvm constraint string to something gcc is expecting.
2686 //TODO: work out platform independent constraints and factor those out
2687 // of the per target tables
2688 // handle multiple constraint codes
2689 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2691 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2693 const char** table = 0;
2695 //Grab the translation table from TargetAsmInfo if it exists
2698 const TargetMachineRegistry::entry* Match =
2699 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2701 //Per platform Target Machines don't exist, so create it
2702 // this must be done only once
2703 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2704 TAsm = TM->getTargetAsmInfo();
2708 table = TAsm->getAsmCBE();
2710 //Search the translation table if it exists
2711 for (int i = 0; table && table[i]; i += 2)
2712 if (c.Codes[0] == table[i])
2715 //default is identity
2719 //TODO: import logic from AsmPrinter.cpp
2720 static std::string gccifyAsm(std::string asmstr) {
2721 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2722 if (asmstr[i] == '\n')
2723 asmstr.replace(i, 1, "\\n");
2724 else if (asmstr[i] == '\t')
2725 asmstr.replace(i, 1, "\\t");
2726 else if (asmstr[i] == '$') {
2727 if (asmstr[i + 1] == '{') {
2728 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2729 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2730 std::string n = "%" +
2731 asmstr.substr(a + 1, b - a - 1) +
2732 asmstr.substr(i + 2, a - i - 2);
2733 asmstr.replace(i, b - i + 1, n);
2736 asmstr.replace(i, 1, "%");
2738 else if (asmstr[i] == '%')//grr
2739 { asmstr.replace(i, 1, "%%"); ++i;}
2744 //TODO: assumptions about what consume arguments from the call are likely wrong
2745 // handle communitivity
2746 void CWriter::visitInlineAsm(CallInst &CI) {
2747 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2748 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2749 std::vector<std::pair<std::string, Value*> > Input;
2750 std::vector<std::pair<std::string, Value*> > Output;
2751 std::string Clobber;
2752 int count = CI.getType() == Type::VoidTy ? 1 : 0;
2753 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2754 E = Constraints.end(); I != E; ++I) {
2755 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2757 InterpretASMConstraint(*I);
2760 assert(0 && "Unknown asm constraint");
2762 case InlineAsm::isInput: {
2764 Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2765 ++count; //consume arg
2769 case InlineAsm::isOutput: {
2771 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2772 count ? CI.getOperand(count) : &CI));
2773 ++count; //consume arg
2777 case InlineAsm::isClobber: {
2779 Clobber += ",\"" + c + "\"";
2785 //fix up the asm string for gcc
2786 std::string asmstr = gccifyAsm(as->getAsmString());
2788 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2790 for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2791 E = Output.end(); I != E; ++I) {
2792 Out << "\"" << I->first << "\"(";
2793 writeOperandRaw(I->second);
2799 for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2800 E = Input.end(); I != E; ++I) {
2801 Out << "\"" << I->first << "\"(";
2802 writeOperandRaw(I->second);
2808 Out << "\n :" << Clobber.substr(1);
2812 void CWriter::visitMallocInst(MallocInst &I) {
2813 assert(0 && "lowerallocations pass didn't work!");
2816 void CWriter::visitAllocaInst(AllocaInst &I) {
2818 printType(Out, I.getType());
2819 Out << ") alloca(sizeof(";
2820 printType(Out, I.getType()->getElementType());
2822 if (I.isArrayAllocation()) {
2824 writeOperand(I.getOperand(0));
2829 void CWriter::visitFreeInst(FreeInst &I) {
2830 assert(0 && "lowerallocations pass didn't work!");
2833 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2834 gep_type_iterator E) {
2835 bool HasImplicitAddress = false;
2836 // If accessing a global value with no indexing, avoid *(&GV) syndrome
2837 if (isa<GlobalValue>(Ptr)) {
2838 HasImplicitAddress = true;
2839 } else if (isDirectAlloca(Ptr)) {
2840 HasImplicitAddress = true;
2844 if (!HasImplicitAddress)
2845 Out << '*'; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2847 writeOperandInternal(Ptr);
2851 const Constant *CI = dyn_cast<Constant>(I.getOperand());
2852 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2855 writeOperandInternal(Ptr);
2857 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2859 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
2862 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2863 "Can only have implicit address with direct accessing");
2865 if (HasImplicitAddress) {
2867 } else if (CI && CI->isNullValue()) {
2868 gep_type_iterator TmpI = I; ++TmpI;
2870 // Print out the -> operator if possible...
2871 if (TmpI != E && isa<StructType>(*TmpI)) {
2872 Out << (HasImplicitAddress ? "." : "->");
2873 Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2879 if (isa<StructType>(*I)) {
2880 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2883 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
2888 void CWriter::visitLoadInst(LoadInst &I) {
2890 if (I.isVolatile()) {
2892 printType(Out, I.getType(), false, "volatile*");
2896 writeOperand(I.getOperand(0));
2902 void CWriter::visitStoreInst(StoreInst &I) {
2904 if (I.isVolatile()) {
2906 printType(Out, I.getOperand(0)->getType(), false, " volatile*");
2909 writeOperand(I.getPointerOperand());
2910 if (I.isVolatile()) Out << ')';
2912 Value *Operand = I.getOperand(0);
2913 Constant *BitMask = 0;
2914 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
2915 if (!ITy->isPowerOf2ByteWidth())
2916 // We have a bit width that doesn't match an even power-of-2 byte
2917 // size. Consequently we must & the value with the type's bit mask
2918 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
2921 writeOperand(Operand);
2924 printConstant(BitMask);
2929 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2931 printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2935 void CWriter::visitVAArgInst(VAArgInst &I) {
2936 Out << "va_arg(*(va_list*)";
2937 writeOperand(I.getOperand(0));
2939 printType(Out, I.getType());
2943 //===----------------------------------------------------------------------===//
2944 // External Interface declaration
2945 //===----------------------------------------------------------------------===//
2947 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2949 CodeGenFileType FileType,
2951 if (FileType != TargetMachine::AssemblyFile) return true;
2953 PM.add(createGCLoweringPass());
2954 PM.add(createLowerAllocationsPass(true));
2955 PM.add(createLowerInvokePass());
2956 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
2957 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2958 PM.add(new CWriter(o));
2959 PM.add(createCollectorMetadataDeleter());