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/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Analysis/ConstantsScanner.h"
31 #include "llvm/Analysis/FindUsedTypes.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/Target/Mangler.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Support/CallSite.h"
44 #include "llvm/Support/CFG.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/FormattedStream.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/Host.h"
51 #include "llvm/Config/config.h"
53 // Some ms header decided to define setjmp as _setjmp, undo this for this file.
59 extern "C" void LLVMInitializeCBackendTarget() {
60 // Register the target.
61 RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
65 class CBEMCAsmInfo : public MCAsmInfo {
69 PrivateGlobalPrefix = "";
72 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
73 /// any unnamed structure types that are used by the program, and merges
74 /// external functions with the same name.
76 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
79 CBackendNameAllUsedStructsAndMergeFunctions()
81 initializeFindUsedTypesPass(*PassRegistry::getPassRegistry());
83 void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequired<FindUsedTypes>();
87 virtual const char *getPassName() const {
88 return "C backend type canonicalizer";
91 virtual bool runOnModule(Module &M);
94 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
96 /// CWriter - This class is the main chunk of code that converts an LLVM
97 /// module to a C translation unit.
98 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
99 formatted_raw_ostream &Out;
100 IntrinsicLowering *IL;
103 const Module *TheModule;
104 const MCAsmInfo* TAsm;
106 const TargetData* TD;
107 std::map<const Type *, std::string> TypeNames;
108 std::map<const ConstantFP *, unsigned> FPConstantMap;
109 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
110 std::set<const Argument*> ByValParams;
112 unsigned OpaqueCounter;
113 DenseMap<const Value*, unsigned> AnonValueNumbers;
114 unsigned NextAnonValueNumber;
118 explicit CWriter(formatted_raw_ostream &o)
119 : FunctionPass(ID), Out(o), IL(0), Mang(0), LI(0),
120 TheModule(0), TAsm(0), TCtx(0), TD(0), OpaqueCounter(0),
121 NextAnonValueNumber(0) {
122 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
126 virtual const char *getPassName() const { return "C backend"; }
128 void getAnalysisUsage(AnalysisUsage &AU) const {
129 AU.addRequired<LoopInfo>();
130 AU.setPreservesAll();
133 virtual bool doInitialization(Module &M);
135 bool runOnFunction(Function &F) {
136 // Do not codegen any 'available_externally' functions at all, they have
137 // definitions outside the translation unit.
138 if (F.hasAvailableExternallyLinkage())
141 LI = &getAnalysis<LoopInfo>();
143 // Get rid of intrinsics we can't handle.
146 // Output all floating point constants that cannot be printed accurately.
147 printFloatingPointConstants(F);
153 virtual bool doFinalization(Module &M) {
160 FPConstantMap.clear();
163 intrinsicPrototypesAlreadyGenerated.clear();
167 raw_ostream &printType(raw_ostream &Out, const Type *Ty,
168 bool isSigned = false,
169 const std::string &VariableName = "",
170 bool IgnoreName = false,
171 const AttrListPtr &PAL = AttrListPtr());
172 raw_ostream &printSimpleType(raw_ostream &Out, const Type *Ty,
174 const std::string &NameSoFar = "");
176 void printStructReturnPointerFunctionType(raw_ostream &Out,
177 const AttrListPtr &PAL,
178 const PointerType *Ty);
180 /// writeOperandDeref - Print the result of dereferencing the specified
181 /// operand with '*'. This is equivalent to printing '*' then using
182 /// writeOperand, but avoids excess syntax in some cases.
183 void writeOperandDeref(Value *Operand) {
184 if (isAddressExposed(Operand)) {
185 // Already something with an address exposed.
186 writeOperandInternal(Operand);
189 writeOperand(Operand);
194 void writeOperand(Value *Operand, bool Static = false);
195 void writeInstComputationInline(Instruction &I);
196 void writeOperandInternal(Value *Operand, bool Static = false);
197 void writeOperandWithCast(Value* Operand, unsigned Opcode);
198 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
199 bool writeInstructionCast(const Instruction &I);
201 void writeMemoryAccess(Value *Operand, const Type *OperandType,
202 bool IsVolatile, unsigned Alignment);
205 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
207 void lowerIntrinsics(Function &F);
209 void printModuleTypes(const TypeSymbolTable &ST);
210 void printContainedStructs(const Type *Ty, std::set<const Type *> &);
211 void printFloatingPointConstants(Function &F);
212 void printFloatingPointConstants(const Constant *C);
213 void printFunctionSignature(const Function *F, bool Prototype);
215 void printFunction(Function &);
216 void printBasicBlock(BasicBlock *BB);
217 void printLoop(Loop *L);
219 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
220 void printConstant(Constant *CPV, bool Static);
221 void printConstantWithCast(Constant *CPV, unsigned Opcode);
222 bool printConstExprCast(const ConstantExpr *CE, bool Static);
223 void printConstantArray(ConstantArray *CPA, bool Static);
224 void printConstantVector(ConstantVector *CV, bool Static);
226 /// isAddressExposed - Return true if the specified value's name needs to
227 /// have its address taken in order to get a C value of the correct type.
228 /// This happens for global variables, byval parameters, and direct allocas.
229 bool isAddressExposed(const Value *V) const {
230 if (const Argument *A = dyn_cast<Argument>(V))
231 return ByValParams.count(A);
232 return isa<GlobalVariable>(V) || isDirectAlloca(V);
235 // isInlinableInst - Attempt to inline instructions into their uses to build
236 // trees as much as possible. To do this, we have to consistently decide
237 // what is acceptable to inline, so that variable declarations don't get
238 // printed and an extra copy of the expr is not emitted.
240 static bool isInlinableInst(const Instruction &I) {
241 // Always inline cmp instructions, even if they are shared by multiple
242 // expressions. GCC generates horrible code if we don't.
246 // Must be an expression, must be used exactly once. If it is dead, we
247 // emit it inline where it would go.
248 if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
249 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
250 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
251 isa<InsertValueInst>(I))
252 // Don't inline a load across a store or other bad things!
255 // Must not be used in inline asm, extractelement, or shufflevector.
257 const Instruction &User = cast<Instruction>(*I.use_back());
258 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
259 isa<ShuffleVectorInst>(User))
263 // Only inline instruction it if it's use is in the same BB as the inst.
264 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
267 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
268 // variables which are accessed with the & operator. This causes GCC to
269 // generate significantly better code than to emit alloca calls directly.
271 static const AllocaInst *isDirectAlloca(const Value *V) {
272 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
274 if (AI->isArrayAllocation())
275 return 0; // FIXME: we can also inline fixed size array allocas!
276 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
281 // isInlineAsm - Check if the instruction is a call to an inline asm chunk.
282 static bool isInlineAsm(const Instruction& I) {
283 if (const CallInst *CI = dyn_cast<CallInst>(&I))
284 return isa<InlineAsm>(CI->getCalledValue());
288 // Instruction visitation functions
289 friend class InstVisitor<CWriter>;
291 void visitReturnInst(ReturnInst &I);
292 void visitBranchInst(BranchInst &I);
293 void visitSwitchInst(SwitchInst &I);
294 void visitIndirectBrInst(IndirectBrInst &I);
295 void visitInvokeInst(InvokeInst &I) {
296 llvm_unreachable("Lowerinvoke pass didn't work!");
299 void visitUnwindInst(UnwindInst &I) {
300 llvm_unreachable("Lowerinvoke pass didn't work!");
302 void visitUnreachableInst(UnreachableInst &I);
304 void visitPHINode(PHINode &I);
305 void visitBinaryOperator(Instruction &I);
306 void visitICmpInst(ICmpInst &I);
307 void visitFCmpInst(FCmpInst &I);
309 void visitCastInst (CastInst &I);
310 void visitSelectInst(SelectInst &I);
311 void visitCallInst (CallInst &I);
312 void visitInlineAsm(CallInst &I);
313 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
315 void visitAllocaInst(AllocaInst &I);
316 void visitLoadInst (LoadInst &I);
317 void visitStoreInst (StoreInst &I);
318 void visitGetElementPtrInst(GetElementPtrInst &I);
319 void visitVAArgInst (VAArgInst &I);
321 void visitInsertElementInst(InsertElementInst &I);
322 void visitExtractElementInst(ExtractElementInst &I);
323 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
325 void visitInsertValueInst(InsertValueInst &I);
326 void visitExtractValueInst(ExtractValueInst &I);
328 void visitInstruction(Instruction &I) {
330 errs() << "C Writer does not know about " << I;
335 void outputLValue(Instruction *I) {
336 Out << " " << GetValueName(I) << " = ";
339 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
340 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
341 BasicBlock *Successor, unsigned Indent);
342 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
344 void printGEPExpression(Value *Ptr, gep_type_iterator I,
345 gep_type_iterator E, bool Static);
347 std::string GetValueName(const Value *Operand);
351 char CWriter::ID = 0;
354 static std::string CBEMangle(const std::string &S) {
357 for (unsigned i = 0, e = S.size(); i != e; ++i)
358 if (isalnum(S[i]) || S[i] == '_') {
362 Result += 'A'+(S[i]&15);
363 Result += 'A'+((S[i]>>4)&15);
370 /// This method inserts names for any unnamed structure types that are used by
371 /// the program, and removes names from structure types that are not used by the
374 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
375 // Get a set of types that are used by the program...
376 SetVector<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
378 // Loop over the module symbol table, removing types from UT that are
379 // already named, and removing names for types that are not used.
381 TypeSymbolTable &TST = M.getTypeSymbolTable();
382 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
384 TypeSymbolTable::iterator I = TI++;
386 // If this isn't a struct or array type, remove it from our set of types
387 // to name. This simplifies emission later.
388 if (!I->second->isStructTy() && !I->second->isOpaqueTy() &&
389 !I->second->isArrayTy()) {
392 // If this is not used, remove it from the symbol table.
393 if (!UT.count(I->second))
396 UT.remove(I->second); // Only keep one name for this type.
400 // UT now contains types that are not named. Loop over it, naming
403 bool Changed = false;
404 unsigned RenameCounter = 0;
405 for (SetVector<const Type *>::const_iterator I = UT.begin(), E = UT.end();
407 if ((*I)->isStructTy() || (*I)->isArrayTy()) {
408 while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
414 // Loop over all external functions and globals. If we have two with
415 // identical names, merge them.
416 // FIXME: This code should disappear when we don't allow values with the same
417 // names when they have different types!
418 std::map<std::string, GlobalValue*> ExtSymbols;
419 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
421 if (GV->isDeclaration() && GV->hasName()) {
422 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
423 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
425 // Found a conflict, replace this global with the previous one.
426 GlobalValue *OldGV = X.first->second;
427 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
428 GV->eraseFromParent();
433 // Do the same for globals.
434 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
436 GlobalVariable *GV = I++;
437 if (GV->isDeclaration() && GV->hasName()) {
438 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
439 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
441 // Found a conflict, replace this global with the previous one.
442 GlobalValue *OldGV = X.first->second;
443 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
444 GV->eraseFromParent();
453 /// printStructReturnPointerFunctionType - This is like printType for a struct
454 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
455 /// print it as "Struct (*)(...)", for struct return functions.
456 void CWriter::printStructReturnPointerFunctionType(raw_ostream &Out,
457 const AttrListPtr &PAL,
458 const PointerType *TheTy) {
459 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
461 raw_string_ostream FunctionInnards(tstr);
462 FunctionInnards << " (*) (";
463 bool PrintedType = false;
465 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
466 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
468 for (++I, ++Idx; I != E; ++I, ++Idx) {
470 FunctionInnards << ", ";
471 const Type *ArgTy = *I;
472 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
473 assert(ArgTy->isPointerTy());
474 ArgTy = cast<PointerType>(ArgTy)->getElementType();
476 printType(FunctionInnards, ArgTy,
477 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
480 if (FTy->isVarArg()) {
482 FunctionInnards << " int"; //dummy argument for empty vararg functs
483 FunctionInnards << ", ...";
484 } else if (!PrintedType) {
485 FunctionInnards << "void";
487 FunctionInnards << ')';
488 printType(Out, RetTy,
489 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
493 CWriter::printSimpleType(raw_ostream &Out, const Type *Ty, bool isSigned,
494 const std::string &NameSoFar) {
495 assert((Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) &&
496 "Invalid type for printSimpleType");
497 switch (Ty->getTypeID()) {
498 case Type::VoidTyID: return Out << "void " << NameSoFar;
499 case Type::IntegerTyID: {
500 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
502 return Out << "bool " << NameSoFar;
503 else if (NumBits <= 8)
504 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
505 else if (NumBits <= 16)
506 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
507 else if (NumBits <= 32)
508 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
509 else if (NumBits <= 64)
510 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
512 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
513 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
516 case Type::FloatTyID: return Out << "float " << NameSoFar;
517 case Type::DoubleTyID: return Out << "double " << NameSoFar;
518 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
519 // present matches host 'long double'.
520 case Type::X86_FP80TyID:
521 case Type::PPC_FP128TyID:
522 case Type::FP128TyID: return Out << "long double " << NameSoFar;
524 case Type::X86_MMXTyID:
525 return printSimpleType(Out, Type::getInt32Ty(Ty->getContext()), isSigned,
526 " __attribute__((vector_size(64))) " + NameSoFar);
528 case Type::VectorTyID: {
529 const VectorType *VTy = cast<VectorType>(Ty);
530 return printSimpleType(Out, VTy->getElementType(), isSigned,
531 " __attribute__((vector_size(" +
532 utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
537 errs() << "Unknown primitive type: " << *Ty << "\n";
543 // Pass the Type* and the variable name and this prints out the variable
546 raw_ostream &CWriter::printType(raw_ostream &Out, const Type *Ty,
547 bool isSigned, const std::string &NameSoFar,
548 bool IgnoreName, const AttrListPtr &PAL) {
549 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || Ty->isVectorTy()) {
550 printSimpleType(Out, Ty, isSigned, NameSoFar);
554 // Check to see if the type is named.
555 if (!IgnoreName || Ty->isOpaqueTy()) {
556 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
557 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
560 switch (Ty->getTypeID()) {
561 case Type::FunctionTyID: {
562 const FunctionType *FTy = cast<FunctionType>(Ty);
564 raw_string_ostream FunctionInnards(tstr);
565 FunctionInnards << " (" << NameSoFar << ") (";
567 for (FunctionType::param_iterator I = FTy->param_begin(),
568 E = FTy->param_end(); I != E; ++I) {
569 const Type *ArgTy = *I;
570 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
571 assert(ArgTy->isPointerTy());
572 ArgTy = cast<PointerType>(ArgTy)->getElementType();
574 if (I != FTy->param_begin())
575 FunctionInnards << ", ";
576 printType(FunctionInnards, ArgTy,
577 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
580 if (FTy->isVarArg()) {
581 if (!FTy->getNumParams())
582 FunctionInnards << " int"; //dummy argument for empty vaarg functs
583 FunctionInnards << ", ...";
584 } else if (!FTy->getNumParams()) {
585 FunctionInnards << "void";
587 FunctionInnards << ')';
588 printType(Out, FTy->getReturnType(),
589 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), FunctionInnards.str());
592 case Type::StructTyID: {
593 const StructType *STy = cast<StructType>(Ty);
594 Out << NameSoFar + " {\n";
596 for (StructType::element_iterator I = STy->element_begin(),
597 E = STy->element_end(); I != E; ++I) {
599 printType(Out, *I, false, "field" + utostr(Idx++));
604 Out << " __attribute__ ((packed))";
608 case Type::PointerTyID: {
609 const PointerType *PTy = cast<PointerType>(Ty);
610 std::string ptrName = "*" + NameSoFar;
612 if (PTy->getElementType()->isArrayTy() ||
613 PTy->getElementType()->isVectorTy())
614 ptrName = "(" + ptrName + ")";
617 // Must be a function ptr cast!
618 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
619 return printType(Out, PTy->getElementType(), false, ptrName);
622 case Type::ArrayTyID: {
623 const ArrayType *ATy = cast<ArrayType>(Ty);
624 unsigned NumElements = ATy->getNumElements();
625 if (NumElements == 0) NumElements = 1;
626 // Arrays are wrapped in structs to allow them to have normal
627 // value semantics (avoiding the array "decay").
628 Out << NameSoFar << " { ";
629 printType(Out, ATy->getElementType(), false,
630 "array[" + utostr(NumElements) + "]");
634 case Type::OpaqueTyID: {
635 std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
636 assert(TypeNames.find(Ty) == TypeNames.end());
637 TypeNames[Ty] = TyName;
638 return Out << TyName << ' ' << NameSoFar;
641 llvm_unreachable("Unhandled case in getTypeProps!");
647 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
649 // As a special case, print the array as a string if it is an array of
650 // ubytes or an array of sbytes with positive values.
652 const Type *ETy = CPA->getType()->getElementType();
653 bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
654 ETy == Type::getInt8Ty(CPA->getContext()));
656 // Make sure the last character is a null char, as automatically added by C
657 if (isString && (CPA->getNumOperands() == 0 ||
658 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
663 // Keep track of whether the last number was a hexadecimal escape.
664 bool LastWasHex = false;
666 // Do not include the last character, which we know is null
667 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
668 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
670 // Print it out literally if it is a printable character. The only thing
671 // to be careful about is when the last letter output was a hex escape
672 // code, in which case we have to be careful not to print out hex digits
673 // explicitly (the C compiler thinks it is a continuation of the previous
674 // character, sheesh...)
676 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
678 if (C == '"' || C == '\\')
679 Out << "\\" << (char)C;
685 case '\n': Out << "\\n"; break;
686 case '\t': Out << "\\t"; break;
687 case '\r': Out << "\\r"; break;
688 case '\v': Out << "\\v"; break;
689 case '\a': Out << "\\a"; break;
690 case '\"': Out << "\\\""; break;
691 case '\'': Out << "\\\'"; break;
694 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
695 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
704 if (CPA->getNumOperands()) {
706 printConstant(cast<Constant>(CPA->getOperand(0)), Static);
707 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
709 printConstant(cast<Constant>(CPA->getOperand(i)), Static);
716 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
718 if (CP->getNumOperands()) {
720 printConstant(cast<Constant>(CP->getOperand(0)), Static);
721 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
723 printConstant(cast<Constant>(CP->getOperand(i)), Static);
729 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
730 // textually as a double (rather than as a reference to a stack-allocated
731 // variable). We decide this by converting CFP to a string and back into a
732 // double, and then checking whether the conversion results in a bit-equal
733 // double to the original value of CFP. This depends on us and the target C
734 // compiler agreeing on the conversion process (which is pretty likely since we
735 // only deal in IEEE FP).
737 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
739 // Do long doubles in hex for now.
740 if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
741 CFP->getType() != Type::getDoubleTy(CFP->getContext()))
743 APFloat APF = APFloat(CFP->getValueAPF()); // copy
744 if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
745 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
746 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
748 sprintf(Buffer, "%a", APF.convertToDouble());
749 if (!strncmp(Buffer, "0x", 2) ||
750 !strncmp(Buffer, "-0x", 3) ||
751 !strncmp(Buffer, "+0x", 3))
752 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
755 std::string StrVal = ftostr(APF);
757 while (StrVal[0] == ' ')
758 StrVal.erase(StrVal.begin());
760 // Check to make sure that the stringized number is not some string like "Inf"
761 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
762 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
763 ((StrVal[0] == '-' || StrVal[0] == '+') &&
764 (StrVal[1] >= '0' && StrVal[1] <= '9')))
765 // Reparse stringized version!
766 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
771 /// Print out the casting for a cast operation. This does the double casting
772 /// necessary for conversion to the destination type, if necessary.
773 /// @brief Print a cast
774 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
775 // Print the destination type cast
777 case Instruction::UIToFP:
778 case Instruction::SIToFP:
779 case Instruction::IntToPtr:
780 case Instruction::Trunc:
781 case Instruction::BitCast:
782 case Instruction::FPExt:
783 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
785 printType(Out, DstTy);
788 case Instruction::ZExt:
789 case Instruction::PtrToInt:
790 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
792 printSimpleType(Out, DstTy, false);
795 case Instruction::SExt:
796 case Instruction::FPToSI: // For these, make sure we get a signed dest
798 printSimpleType(Out, DstTy, true);
802 llvm_unreachable("Invalid cast opcode");
805 // Print the source type cast
807 case Instruction::UIToFP:
808 case Instruction::ZExt:
810 printSimpleType(Out, SrcTy, false);
813 case Instruction::SIToFP:
814 case Instruction::SExt:
816 printSimpleType(Out, SrcTy, true);
819 case Instruction::IntToPtr:
820 case Instruction::PtrToInt:
821 // Avoid "cast to pointer from integer of different size" warnings
822 Out << "(unsigned long)";
824 case Instruction::Trunc:
825 case Instruction::BitCast:
826 case Instruction::FPExt:
827 case Instruction::FPTrunc:
828 case Instruction::FPToSI:
829 case Instruction::FPToUI:
830 break; // These don't need a source cast.
832 llvm_unreachable("Invalid cast opcode");
837 // printConstant - The LLVM Constant to C Constant converter.
838 void CWriter::printConstant(Constant *CPV, bool Static) {
839 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
840 switch (CE->getOpcode()) {
841 case Instruction::Trunc:
842 case Instruction::ZExt:
843 case Instruction::SExt:
844 case Instruction::FPTrunc:
845 case Instruction::FPExt:
846 case Instruction::UIToFP:
847 case Instruction::SIToFP:
848 case Instruction::FPToUI:
849 case Instruction::FPToSI:
850 case Instruction::PtrToInt:
851 case Instruction::IntToPtr:
852 case Instruction::BitCast:
854 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
855 if (CE->getOpcode() == Instruction::SExt &&
856 CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
857 // Make sure we really sext from bool here by subtracting from 0
860 printConstant(CE->getOperand(0), Static);
861 if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
862 (CE->getOpcode() == Instruction::Trunc ||
863 CE->getOpcode() == Instruction::FPToUI ||
864 CE->getOpcode() == Instruction::FPToSI ||
865 CE->getOpcode() == Instruction::PtrToInt)) {
866 // Make sure we really truncate to bool here by anding with 1
872 case Instruction::GetElementPtr:
874 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
875 gep_type_end(CPV), Static);
878 case Instruction::Select:
880 printConstant(CE->getOperand(0), Static);
882 printConstant(CE->getOperand(1), Static);
884 printConstant(CE->getOperand(2), Static);
887 case Instruction::Add:
888 case Instruction::FAdd:
889 case Instruction::Sub:
890 case Instruction::FSub:
891 case Instruction::Mul:
892 case Instruction::FMul:
893 case Instruction::SDiv:
894 case Instruction::UDiv:
895 case Instruction::FDiv:
896 case Instruction::URem:
897 case Instruction::SRem:
898 case Instruction::FRem:
899 case Instruction::And:
900 case Instruction::Or:
901 case Instruction::Xor:
902 case Instruction::ICmp:
903 case Instruction::Shl:
904 case Instruction::LShr:
905 case Instruction::AShr:
908 bool NeedsClosingParens = printConstExprCast(CE, Static);
909 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
910 switch (CE->getOpcode()) {
911 case Instruction::Add:
912 case Instruction::FAdd: Out << " + "; break;
913 case Instruction::Sub:
914 case Instruction::FSub: Out << " - "; break;
915 case Instruction::Mul:
916 case Instruction::FMul: Out << " * "; break;
917 case Instruction::URem:
918 case Instruction::SRem:
919 case Instruction::FRem: Out << " % "; break;
920 case Instruction::UDiv:
921 case Instruction::SDiv:
922 case Instruction::FDiv: Out << " / "; break;
923 case Instruction::And: Out << " & "; break;
924 case Instruction::Or: Out << " | "; break;
925 case Instruction::Xor: Out << " ^ "; break;
926 case Instruction::Shl: Out << " << "; break;
927 case Instruction::LShr:
928 case Instruction::AShr: Out << " >> "; break;
929 case Instruction::ICmp:
930 switch (CE->getPredicate()) {
931 case ICmpInst::ICMP_EQ: Out << " == "; break;
932 case ICmpInst::ICMP_NE: Out << " != "; break;
933 case ICmpInst::ICMP_SLT:
934 case ICmpInst::ICMP_ULT: Out << " < "; break;
935 case ICmpInst::ICMP_SLE:
936 case ICmpInst::ICMP_ULE: Out << " <= "; break;
937 case ICmpInst::ICMP_SGT:
938 case ICmpInst::ICMP_UGT: Out << " > "; break;
939 case ICmpInst::ICMP_SGE:
940 case ICmpInst::ICMP_UGE: Out << " >= "; break;
941 default: llvm_unreachable("Illegal ICmp predicate");
944 default: llvm_unreachable("Illegal opcode here!");
946 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
947 if (NeedsClosingParens)
952 case Instruction::FCmp: {
954 bool NeedsClosingParens = printConstExprCast(CE, Static);
955 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
957 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
961 switch (CE->getPredicate()) {
962 default: llvm_unreachable("Illegal FCmp predicate");
963 case FCmpInst::FCMP_ORD: op = "ord"; break;
964 case FCmpInst::FCMP_UNO: op = "uno"; break;
965 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
966 case FCmpInst::FCMP_UNE: op = "une"; break;
967 case FCmpInst::FCMP_ULT: op = "ult"; break;
968 case FCmpInst::FCMP_ULE: op = "ule"; break;
969 case FCmpInst::FCMP_UGT: op = "ugt"; break;
970 case FCmpInst::FCMP_UGE: op = "uge"; break;
971 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
972 case FCmpInst::FCMP_ONE: op = "one"; break;
973 case FCmpInst::FCMP_OLT: op = "olt"; break;
974 case FCmpInst::FCMP_OLE: op = "ole"; break;
975 case FCmpInst::FCMP_OGT: op = "ogt"; break;
976 case FCmpInst::FCMP_OGE: op = "oge"; break;
978 Out << "llvm_fcmp_" << op << "(";
979 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
981 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
984 if (NeedsClosingParens)
991 errs() << "CWriter Error: Unhandled constant expression: "
996 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
998 printType(Out, CPV->getType()); // sign doesn't matter
1000 if (!CPV->getType()->isVectorTy()) {
1008 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1009 const Type* Ty = CI->getType();
1010 if (Ty == Type::getInt1Ty(CPV->getContext()))
1011 Out << (CI->getZExtValue() ? '1' : '0');
1012 else if (Ty == Type::getInt32Ty(CPV->getContext()))
1013 Out << CI->getZExtValue() << 'u';
1014 else if (Ty->getPrimitiveSizeInBits() > 32)
1015 Out << CI->getZExtValue() << "ull";
1018 printSimpleType(Out, Ty, false) << ')';
1019 if (CI->isMinValue(true))
1020 Out << CI->getZExtValue() << 'u';
1022 Out << CI->getSExtValue();
1028 switch (CPV->getType()->getTypeID()) {
1029 case Type::FloatTyID:
1030 case Type::DoubleTyID:
1031 case Type::X86_FP80TyID:
1032 case Type::PPC_FP128TyID:
1033 case Type::FP128TyID: {
1034 ConstantFP *FPC = cast<ConstantFP>(CPV);
1035 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
1036 if (I != FPConstantMap.end()) {
1037 // Because of FP precision problems we must load from a stack allocated
1038 // value that holds the value in hex.
1039 Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
1041 FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
1044 << "*)&FPConstant" << I->second << ')';
1047 if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
1048 V = FPC->getValueAPF().convertToFloat();
1049 else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
1050 V = FPC->getValueAPF().convertToDouble();
1052 // Long double. Convert the number to double, discarding precision.
1053 // This is not awesome, but it at least makes the CBE output somewhat
1055 APFloat Tmp = FPC->getValueAPF();
1057 Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
1058 V = Tmp.convertToDouble();
1064 // FIXME the actual NaN bits should be emitted.
1065 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
1067 const unsigned long QuietNaN = 0x7ff8UL;
1068 //const unsigned long SignalNaN = 0x7ff4UL;
1070 // We need to grab the first part of the FP #
1073 uint64_t ll = DoubleToBits(V);
1074 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
1076 std::string Num(&Buffer[0], &Buffer[6]);
1077 unsigned long Val = strtoul(Num.c_str(), 0, 16);
1079 if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
1080 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
1081 << Buffer << "\") /*nan*/ ";
1083 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
1084 << Buffer << "\") /*nan*/ ";
1085 } else if (IsInf(V)) {
1087 if (V < 0) Out << '-';
1088 Out << "LLVM_INF" <<
1089 (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
1093 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1094 // Print out the constant as a floating point number.
1096 sprintf(Buffer, "%a", V);
1099 Num = ftostr(FPC->getValueAPF());
1107 case Type::ArrayTyID:
1108 // Use C99 compound expression literal initializer syntax.
1111 printType(Out, CPV->getType());
1114 Out << "{ "; // Arrays are wrapped in struct types.
1115 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1116 printConstantArray(CA, Static);
1118 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1119 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1121 if (AT->getNumElements()) {
1123 Constant *CZ = Constant::getNullValue(AT->getElementType());
1124 printConstant(CZ, Static);
1125 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1127 printConstant(CZ, Static);
1132 Out << " }"; // Arrays are wrapped in struct types.
1135 case Type::VectorTyID:
1136 // Use C99 compound expression literal initializer syntax.
1139 printType(Out, CPV->getType());
1142 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1143 printConstantVector(CV, Static);
1145 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1146 const VectorType *VT = cast<VectorType>(CPV->getType());
1148 Constant *CZ = Constant::getNullValue(VT->getElementType());
1149 printConstant(CZ, Static);
1150 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1152 printConstant(CZ, Static);
1158 case Type::StructTyID:
1159 // Use C99 compound expression literal initializer syntax.
1162 printType(Out, CPV->getType());
1165 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1166 const StructType *ST = cast<StructType>(CPV->getType());
1168 if (ST->getNumElements()) {
1170 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1171 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1173 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1179 if (CPV->getNumOperands()) {
1181 printConstant(cast<Constant>(CPV->getOperand(0)), Static);
1182 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1184 printConstant(cast<Constant>(CPV->getOperand(i)), Static);
1191 case Type::PointerTyID:
1192 if (isa<ConstantPointerNull>(CPV)) {
1194 printType(Out, CPV->getType()); // sign doesn't matter
1195 Out << ")/*NULL*/0)";
1197 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1198 writeOperand(GV, Static);
1204 errs() << "Unknown constant type: " << *CPV << "\n";
1206 llvm_unreachable(0);
1210 // Some constant expressions need to be casted back to the original types
1211 // because their operands were casted to the expected type. This function takes
1212 // care of detecting that case and printing the cast for the ConstantExpr.
1213 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
1214 bool NeedsExplicitCast = false;
1215 const Type *Ty = CE->getOperand(0)->getType();
1216 bool TypeIsSigned = false;
1217 switch (CE->getOpcode()) {
1218 case Instruction::Add:
1219 case Instruction::Sub:
1220 case Instruction::Mul:
1221 // We need to cast integer arithmetic so that it is always performed
1222 // as unsigned, to avoid undefined behavior on overflow.
1223 case Instruction::LShr:
1224 case Instruction::URem:
1225 case Instruction::UDiv: NeedsExplicitCast = true; break;
1226 case Instruction::AShr:
1227 case Instruction::SRem:
1228 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1229 case Instruction::SExt:
1231 NeedsExplicitCast = true;
1232 TypeIsSigned = true;
1234 case Instruction::ZExt:
1235 case Instruction::Trunc:
1236 case Instruction::FPTrunc:
1237 case Instruction::FPExt:
1238 case Instruction::UIToFP:
1239 case Instruction::SIToFP:
1240 case Instruction::FPToUI:
1241 case Instruction::FPToSI:
1242 case Instruction::PtrToInt:
1243 case Instruction::IntToPtr:
1244 case Instruction::BitCast:
1246 NeedsExplicitCast = true;
1250 if (NeedsExplicitCast) {
1252 if (Ty->isIntegerTy() && Ty != Type::getInt1Ty(Ty->getContext()))
1253 printSimpleType(Out, Ty, TypeIsSigned);
1255 printType(Out, Ty); // not integer, sign doesn't matter
1258 return NeedsExplicitCast;
1261 // Print a constant assuming that it is the operand for a given Opcode. The
1262 // opcodes that care about sign need to cast their operands to the expected
1263 // type before the operation proceeds. This function does the casting.
1264 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1266 // Extract the operand's type, we'll need it.
1267 const Type* OpTy = CPV->getType();
1269 // Indicate whether to do the cast or not.
1270 bool shouldCast = false;
1271 bool typeIsSigned = false;
1273 // Based on the Opcode for which this Constant is being written, determine
1274 // the new type to which the operand should be casted by setting the value
1275 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1279 // for most instructions, it doesn't matter
1281 case Instruction::Add:
1282 case Instruction::Sub:
1283 case Instruction::Mul:
1284 // We need to cast integer arithmetic so that it is always performed
1285 // as unsigned, to avoid undefined behavior on overflow.
1286 case Instruction::LShr:
1287 case Instruction::UDiv:
1288 case Instruction::URem:
1291 case Instruction::AShr:
1292 case Instruction::SDiv:
1293 case Instruction::SRem:
1295 typeIsSigned = true;
1299 // Write out the casted constant if we should, otherwise just write the
1303 printSimpleType(Out, OpTy, typeIsSigned);
1305 printConstant(CPV, false);
1308 printConstant(CPV, false);
1311 std::string CWriter::GetValueName(const Value *Operand) {
1313 // Resolve potential alias.
1314 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Operand)) {
1315 if (const Value *V = GA->resolveAliasedGlobal(false))
1319 // Mangle globals with the standard mangler interface for LLC compatibility.
1320 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand)) {
1321 SmallString<128> Str;
1322 Mang->getNameWithPrefix(Str, GV, false);
1323 return CBEMangle(Str.str().str());
1326 std::string Name = Operand->getName();
1328 if (Name.empty()) { // Assign unique names to local temporaries.
1329 unsigned &No = AnonValueNumbers[Operand];
1331 No = ++NextAnonValueNumber;
1332 Name = "tmp__" + utostr(No);
1335 std::string VarName;
1336 VarName.reserve(Name.capacity());
1338 for (std::string::iterator I = Name.begin(), E = Name.end();
1342 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1343 (ch >= '0' && ch <= '9') || ch == '_')) {
1345 sprintf(buffer, "_%x_", ch);
1351 return "llvm_cbe_" + VarName;
1354 /// writeInstComputationInline - Emit the computation for the specified
1355 /// instruction inline, with no destination provided.
1356 void CWriter::writeInstComputationInline(Instruction &I) {
1357 // We can't currently support integer types other than 1, 8, 16, 32, 64.
1359 const Type *Ty = I.getType();
1360 if (Ty->isIntegerTy() && (Ty!=Type::getInt1Ty(I.getContext()) &&
1361 Ty!=Type::getInt8Ty(I.getContext()) &&
1362 Ty!=Type::getInt16Ty(I.getContext()) &&
1363 Ty!=Type::getInt32Ty(I.getContext()) &&
1364 Ty!=Type::getInt64Ty(I.getContext()))) {
1365 report_fatal_error("The C backend does not currently support integer "
1366 "types of widths other than 1, 8, 16, 32, 64.\n"
1367 "This is being tracked as PR 4158.");
1370 // If this is a non-trivial bool computation, make sure to truncate down to
1371 // a 1 bit value. This is important because we want "add i1 x, y" to return
1372 // "0" when x and y are true, not "2" for example.
1373 bool NeedBoolTrunc = false;
1374 if (I.getType() == Type::getInt1Ty(I.getContext()) &&
1375 !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1376 NeedBoolTrunc = true;
1388 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
1389 if (Instruction *I = dyn_cast<Instruction>(Operand))
1390 // Should we inline this instruction to build a tree?
1391 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1393 writeInstComputationInline(*I);
1398 Constant* CPV = dyn_cast<Constant>(Operand);
1400 if (CPV && !isa<GlobalValue>(CPV))
1401 printConstant(CPV, Static);
1403 Out << GetValueName(Operand);
1406 void CWriter::writeOperand(Value *Operand, bool Static) {
1407 bool isAddressImplicit = isAddressExposed(Operand);
1408 if (isAddressImplicit)
1409 Out << "(&"; // Global variables are referenced as their addresses by llvm
1411 writeOperandInternal(Operand, Static);
1413 if (isAddressImplicit)
1417 // Some instructions need to have their result value casted back to the
1418 // original types because their operands were casted to the expected type.
1419 // This function takes care of detecting that case and printing the cast
1420 // for the Instruction.
1421 bool CWriter::writeInstructionCast(const Instruction &I) {
1422 const Type *Ty = I.getOperand(0)->getType();
1423 switch (I.getOpcode()) {
1424 case Instruction::Add:
1425 case Instruction::Sub:
1426 case Instruction::Mul:
1427 // We need to cast integer arithmetic so that it is always performed
1428 // as unsigned, to avoid undefined behavior on overflow.
1429 case Instruction::LShr:
1430 case Instruction::URem:
1431 case Instruction::UDiv:
1433 printSimpleType(Out, Ty, false);
1436 case Instruction::AShr:
1437 case Instruction::SRem:
1438 case Instruction::SDiv:
1440 printSimpleType(Out, Ty, true);
1448 // Write the operand with a cast to another type based on the Opcode being used.
1449 // This will be used in cases where an instruction has specific type
1450 // requirements (usually signedness) for its operands.
1451 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1453 // Extract the operand's type, we'll need it.
1454 const Type* OpTy = Operand->getType();
1456 // Indicate whether to do the cast or not.
1457 bool shouldCast = false;
1459 // Indicate whether the cast should be to a signed type or not.
1460 bool castIsSigned = false;
1462 // Based on the Opcode for which this Operand is being written, determine
1463 // the new type to which the operand should be casted by setting the value
1464 // of OpTy. If we change OpTy, also set shouldCast to true.
1467 // for most instructions, it doesn't matter
1469 case Instruction::Add:
1470 case Instruction::Sub:
1471 case Instruction::Mul:
1472 // We need to cast integer arithmetic so that it is always performed
1473 // as unsigned, to avoid undefined behavior on overflow.
1474 case Instruction::LShr:
1475 case Instruction::UDiv:
1476 case Instruction::URem: // Cast to unsigned first
1478 castIsSigned = false;
1480 case Instruction::GetElementPtr:
1481 case Instruction::AShr:
1482 case Instruction::SDiv:
1483 case Instruction::SRem: // Cast to signed first
1485 castIsSigned = true;
1489 // Write out the casted operand if we should, otherwise just write the
1493 printSimpleType(Out, OpTy, castIsSigned);
1495 writeOperand(Operand);
1498 writeOperand(Operand);
1501 // Write the operand with a cast to another type based on the icmp predicate
1503 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1504 // This has to do a cast to ensure the operand has the right signedness.
1505 // Also, if the operand is a pointer, we make sure to cast to an integer when
1506 // doing the comparison both for signedness and so that the C compiler doesn't
1507 // optimize things like "p < NULL" to false (p may contain an integer value
1509 bool shouldCast = Cmp.isRelational();
1511 // Write out the casted operand if we should, otherwise just write the
1514 writeOperand(Operand);
1518 // Should this be a signed comparison? If so, convert to signed.
1519 bool castIsSigned = Cmp.isSigned();
1521 // If the operand was a pointer, convert to a large integer type.
1522 const Type* OpTy = Operand->getType();
1523 if (OpTy->isPointerTy())
1524 OpTy = TD->getIntPtrType(Operand->getContext());
1527 printSimpleType(Out, OpTy, castIsSigned);
1529 writeOperand(Operand);
1533 // generateCompilerSpecificCode - This is where we add conditional compilation
1534 // directives to cater to specific compilers as need be.
1536 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
1537 const TargetData *TD) {
1538 // Alloca is hard to get, and we don't want to include stdlib.h here.
1539 Out << "/* get a declaration for alloca */\n"
1540 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1541 << "#define alloca(x) __builtin_alloca((x))\n"
1542 << "#define _alloca(x) __builtin_alloca((x))\n"
1543 << "#elif defined(__APPLE__)\n"
1544 << "extern void *__builtin_alloca(unsigned long);\n"
1545 << "#define alloca(x) __builtin_alloca(x)\n"
1546 << "#define longjmp _longjmp\n"
1547 << "#define setjmp _setjmp\n"
1548 << "#elif defined(__sun__)\n"
1549 << "#if defined(__sparcv9)\n"
1550 << "extern void *__builtin_alloca(unsigned long);\n"
1552 << "extern void *__builtin_alloca(unsigned int);\n"
1554 << "#define alloca(x) __builtin_alloca(x)\n"
1555 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
1556 << "#define alloca(x) __builtin_alloca(x)\n"
1557 << "#elif defined(_MSC_VER)\n"
1558 << "#define inline _inline\n"
1559 << "#define alloca(x) _alloca(x)\n"
1561 << "#include <alloca.h>\n"
1564 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1565 // If we aren't being compiled with GCC, just drop these attributes.
1566 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1567 << "#define __attribute__(X)\n"
1570 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1571 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1572 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1573 << "#elif defined(__GNUC__)\n"
1574 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1576 << "#define __EXTERNAL_WEAK__\n"
1579 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1580 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1581 << "#define __ATTRIBUTE_WEAK__\n"
1582 << "#elif defined(__GNUC__)\n"
1583 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1585 << "#define __ATTRIBUTE_WEAK__\n"
1588 // Add hidden visibility support. FIXME: APPLE_CC?
1589 Out << "#if defined(__GNUC__)\n"
1590 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1593 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1594 // From the GCC documentation:
1596 // double __builtin_nan (const char *str)
1598 // This is an implementation of the ISO C99 function nan.
1600 // Since ISO C99 defines this function in terms of strtod, which we do
1601 // not implement, a description of the parsing is in order. The string is
1602 // parsed as by strtol; that is, the base is recognized by leading 0 or
1603 // 0x prefixes. The number parsed is placed in the significand such that
1604 // the least significant bit of the number is at the least significant
1605 // bit of the significand. The number is truncated to fit the significand
1606 // field provided. The significand is forced to be a quiet NaN.
1608 // This function, if given a string literal, is evaluated early enough
1609 // that it is considered a compile-time constant.
1611 // float __builtin_nanf (const char *str)
1613 // Similar to __builtin_nan, except the return type is float.
1615 // double __builtin_inf (void)
1617 // Similar to __builtin_huge_val, except a warning is generated if the
1618 // target floating-point format does not support infinities. This
1619 // function is suitable for implementing the ISO C99 macro INFINITY.
1621 // float __builtin_inff (void)
1623 // Similar to __builtin_inf, except the return type is float.
1624 Out << "#ifdef __GNUC__\n"
1625 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1626 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1627 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1628 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1629 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1630 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1631 << "#define LLVM_PREFETCH(addr,rw,locality) "
1632 "__builtin_prefetch(addr,rw,locality)\n"
1633 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1634 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1635 << "#define LLVM_ASM __asm__\n"
1637 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1638 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1639 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1640 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1641 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1642 << "#define LLVM_INFF 0.0F /* Float */\n"
1643 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1644 << "#define __ATTRIBUTE_CTOR__\n"
1645 << "#define __ATTRIBUTE_DTOR__\n"
1646 << "#define LLVM_ASM(X)\n"
1649 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1650 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1651 << "#define __builtin_stack_restore(X) /* noop */\n"
1654 // Output typedefs for 128-bit integers. If these are needed with a
1655 // 32-bit target or with a C compiler that doesn't support mode(TI),
1656 // more drastic measures will be needed.
1657 Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
1658 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1659 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1662 // Output target-specific code that should be inserted into main.
1663 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1666 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1667 /// the StaticTors set.
1668 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1669 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1670 if (!InitList) return;
1672 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1673 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1674 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1676 if (CS->getOperand(1)->isNullValue())
1677 return; // Found a null terminator, exit printing.
1678 Constant *FP = CS->getOperand(1);
1679 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1681 FP = CE->getOperand(0);
1682 if (Function *F = dyn_cast<Function>(FP))
1683 StaticTors.insert(F);
1687 enum SpecialGlobalClass {
1689 GlobalCtors, GlobalDtors,
1693 /// getGlobalVariableClass - If this is a global that is specially recognized
1694 /// by LLVM, return a code that indicates how we should handle it.
1695 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1696 // If this is a global ctors/dtors list, handle it now.
1697 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1698 if (GV->getName() == "llvm.global_ctors")
1700 else if (GV->getName() == "llvm.global_dtors")
1704 // Otherwise, if it is other metadata, don't print it. This catches things
1705 // like debug information.
1706 if (GV->getSection() == "llvm.metadata")
1712 // PrintEscapedString - Print each character of the specified string, escaping
1713 // it if it is not printable or if it is an escape char.
1714 static void PrintEscapedString(const char *Str, unsigned Length,
1716 for (unsigned i = 0; i != Length; ++i) {
1717 unsigned char C = Str[i];
1718 if (isprint(C) && C != '\\' && C != '"')
1727 Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1731 // PrintEscapedString - Print each character of the specified string, escaping
1732 // it if it is not printable or if it is an escape char.
1733 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
1734 PrintEscapedString(Str.c_str(), Str.size(), Out);
1737 bool CWriter::doInitialization(Module &M) {
1738 FunctionPass::doInitialization(M);
1743 TD = new TargetData(&M);
1744 IL = new IntrinsicLowering(*TD);
1745 IL->AddPrototypes(M);
1748 std::string Triple = TheModule->getTargetTriple();
1750 Triple = llvm::sys::getHostTriple();
1753 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
1754 TAsm = Match->createAsmInfo(Triple);
1756 TAsm = new CBEMCAsmInfo();
1757 TCtx = new MCContext(*TAsm, NULL);
1758 Mang = new Mangler(*TCtx, *TD);
1760 // Keep track of which functions are static ctors/dtors so they can have
1761 // an attribute added to their prototypes.
1762 std::set<Function*> StaticCtors, StaticDtors;
1763 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1765 switch (getGlobalVariableClass(I)) {
1768 FindStaticTors(I, StaticCtors);
1771 FindStaticTors(I, StaticDtors);
1776 // get declaration for alloca
1777 Out << "/* Provide Declarations */\n";
1778 Out << "#include <stdarg.h>\n"; // Varargs support
1779 Out << "#include <setjmp.h>\n"; // Unwind support
1780 generateCompilerSpecificCode(Out, TD);
1782 // Provide a definition for `bool' if not compiling with a C++ compiler.
1784 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1786 << "\n\n/* Support for floating point constants */\n"
1787 << "typedef unsigned long long ConstantDoubleTy;\n"
1788 << "typedef unsigned int ConstantFloatTy;\n"
1789 << "typedef struct { unsigned long long f1; unsigned short f2; "
1790 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1791 // This is used for both kinds of 128-bit long double; meaning differs.
1792 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1793 " ConstantFP128Ty;\n"
1794 << "\n\n/* Global Declarations */\n";
1796 // First output all the declarations for the program, because C requires
1797 // Functions & globals to be declared before they are used.
1799 if (!M.getModuleInlineAsm().empty()) {
1800 Out << "/* Module asm statements */\n"
1803 // Split the string into lines, to make it easier to read the .ll file.
1804 std::string Asm = M.getModuleInlineAsm();
1806 size_t NewLine = Asm.find_first_of('\n', CurPos);
1807 while (NewLine != std::string::npos) {
1808 // We found a newline, print the portion of the asm string from the
1809 // last newline up to this newline.
1811 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1815 NewLine = Asm.find_first_of('\n', CurPos);
1818 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1820 << "/* End Module asm statements */\n";
1823 // Loop over the symbol table, emitting all named constants...
1824 printModuleTypes(M.getTypeSymbolTable());
1826 // Global variable declarations...
1827 if (!M.global_empty()) {
1828 Out << "\n/* External Global Variable Declarations */\n";
1829 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1832 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1833 I->hasCommonLinkage())
1835 else if (I->hasDLLImportLinkage())
1836 Out << "__declspec(dllimport) ";
1838 continue; // Internal Global
1840 // Thread Local Storage
1841 if (I->isThreadLocal())
1844 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1846 if (I->hasExternalWeakLinkage())
1847 Out << " __EXTERNAL_WEAK__";
1852 // Function declarations
1853 Out << "\n/* Function Declarations */\n";
1854 Out << "double fmod(double, double);\n"; // Support for FP rem
1855 Out << "float fmodf(float, float);\n";
1856 Out << "long double fmodl(long double, long double);\n";
1858 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1859 // Don't print declarations for intrinsic functions.
1860 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1861 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1862 if (I->hasExternalWeakLinkage())
1864 printFunctionSignature(I, true);
1865 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1866 Out << " __ATTRIBUTE_WEAK__";
1867 if (I->hasExternalWeakLinkage())
1868 Out << " __EXTERNAL_WEAK__";
1869 if (StaticCtors.count(I))
1870 Out << " __ATTRIBUTE_CTOR__";
1871 if (StaticDtors.count(I))
1872 Out << " __ATTRIBUTE_DTOR__";
1873 if (I->hasHiddenVisibility())
1874 Out << " __HIDDEN__";
1876 if (I->hasName() && I->getName()[0] == 1)
1877 Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
1883 // Output the global variable declarations
1884 if (!M.global_empty()) {
1885 Out << "\n\n/* Global Variable Declarations */\n";
1886 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1888 if (!I->isDeclaration()) {
1889 // Ignore special globals, such as debug info.
1890 if (getGlobalVariableClass(I))
1893 if (I->hasLocalLinkage())
1898 // Thread Local Storage
1899 if (I->isThreadLocal())
1902 printType(Out, I->getType()->getElementType(), false,
1905 if (I->hasLinkOnceLinkage())
1906 Out << " __attribute__((common))";
1907 else if (I->hasCommonLinkage()) // FIXME is this right?
1908 Out << " __ATTRIBUTE_WEAK__";
1909 else if (I->hasWeakLinkage())
1910 Out << " __ATTRIBUTE_WEAK__";
1911 else if (I->hasExternalWeakLinkage())
1912 Out << " __EXTERNAL_WEAK__";
1913 if (I->hasHiddenVisibility())
1914 Out << " __HIDDEN__";
1919 // Output the global variable definitions and contents...
1920 if (!M.global_empty()) {
1921 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1922 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1924 if (!I->isDeclaration()) {
1925 // Ignore special globals, such as debug info.
1926 if (getGlobalVariableClass(I))
1929 if (I->hasLocalLinkage())
1931 else if (I->hasDLLImportLinkage())
1932 Out << "__declspec(dllimport) ";
1933 else if (I->hasDLLExportLinkage())
1934 Out << "__declspec(dllexport) ";
1936 // Thread Local Storage
1937 if (I->isThreadLocal())
1940 printType(Out, I->getType()->getElementType(), false,
1942 if (I->hasLinkOnceLinkage())
1943 Out << " __attribute__((common))";
1944 else if (I->hasWeakLinkage())
1945 Out << " __ATTRIBUTE_WEAK__";
1946 else if (I->hasCommonLinkage())
1947 Out << " __ATTRIBUTE_WEAK__";
1949 if (I->hasHiddenVisibility())
1950 Out << " __HIDDEN__";
1952 // If the initializer is not null, emit the initializer. If it is null,
1953 // we try to avoid emitting large amounts of zeros. The problem with
1954 // this, however, occurs when the variable has weak linkage. In this
1955 // case, the assembler will complain about the variable being both weak
1956 // and common, so we disable this optimization.
1957 // FIXME common linkage should avoid this problem.
1958 if (!I->getInitializer()->isNullValue()) {
1960 writeOperand(I->getInitializer(), true);
1961 } else if (I->hasWeakLinkage()) {
1962 // We have to specify an initializer, but it doesn't have to be
1963 // complete. If the value is an aggregate, print out { 0 }, and let
1964 // the compiler figure out the rest of the zeros.
1966 if (I->getInitializer()->getType()->isStructTy() ||
1967 I->getInitializer()->getType()->isVectorTy()) {
1969 } else if (I->getInitializer()->getType()->isArrayTy()) {
1970 // As with structs and vectors, but with an extra set of braces
1971 // because arrays are wrapped in structs.
1974 // Just print it out normally.
1975 writeOperand(I->getInitializer(), true);
1983 Out << "\n\n/* Function Bodies */\n";
1985 // Emit some helper functions for dealing with FCMP instruction's
1987 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1988 Out << "return X == X && Y == Y; }\n";
1989 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1990 Out << "return X != X || Y != Y; }\n";
1991 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1992 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1993 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1994 Out << "return X != Y; }\n";
1995 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1996 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1997 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1998 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1999 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
2000 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
2001 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
2002 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
2003 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
2004 Out << "return X == Y ; }\n";
2005 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
2006 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
2007 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
2008 Out << "return X < Y ; }\n";
2009 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
2010 Out << "return X > Y ; }\n";
2011 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
2012 Out << "return X <= Y ; }\n";
2013 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
2014 Out << "return X >= Y ; }\n";
2019 /// Output all floating point constants that cannot be printed accurately...
2020 void CWriter::printFloatingPointConstants(Function &F) {
2021 // Scan the module for floating point constants. If any FP constant is used
2022 // in the function, we want to redirect it here so that we do not depend on
2023 // the precision of the printed form, unless the printed form preserves
2026 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
2028 printFloatingPointConstants(*I);
2033 void CWriter::printFloatingPointConstants(const Constant *C) {
2034 // If this is a constant expression, recursively check for constant fp values.
2035 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2036 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2037 printFloatingPointConstants(CE->getOperand(i));
2041 // Otherwise, check for a FP constant that we need to print.
2042 const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
2044 // Do not put in FPConstantMap if safe.
2045 isFPCSafeToPrint(FPC) ||
2046 // Already printed this constant?
2047 FPConstantMap.count(FPC))
2050 FPConstantMap[FPC] = FPCounter; // Number the FP constants
2052 if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
2053 double Val = FPC->getValueAPF().convertToDouble();
2054 uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
2055 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
2056 << " = 0x" << utohexstr(i)
2057 << "ULL; /* " << Val << " */\n";
2058 } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
2059 float Val = FPC->getValueAPF().convertToFloat();
2060 uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
2062 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
2063 << " = 0x" << utohexstr(i)
2064 << "U; /* " << Val << " */\n";
2065 } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
2066 // api needed to prevent premature destruction
2067 APInt api = FPC->getValueAPF().bitcastToAPInt();
2068 const uint64_t *p = api.getRawData();
2069 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
2070 << " = { 0x" << utohexstr(p[0])
2071 << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
2072 << "}; /* Long double constant */\n";
2073 } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext()) ||
2074 FPC->getType() == Type::getFP128Ty(FPC->getContext())) {
2075 APInt api = FPC->getValueAPF().bitcastToAPInt();
2076 const uint64_t *p = api.getRawData();
2077 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
2079 << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
2080 << "}; /* Long double constant */\n";
2083 llvm_unreachable("Unknown float type!");
2089 /// printSymbolTable - Run through symbol table looking for type names. If a
2090 /// type name is found, emit its declaration...
2092 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
2093 Out << "/* Helper union for bitcasts */\n";
2094 Out << "typedef union {\n";
2095 Out << " unsigned int Int32;\n";
2096 Out << " unsigned long long Int64;\n";
2097 Out << " float Float;\n";
2098 Out << " double Double;\n";
2099 Out << "} llvmBitCastUnion;\n";
2101 // We are only interested in the type plane of the symbol table.
2102 TypeSymbolTable::const_iterator I = TST.begin();
2103 TypeSymbolTable::const_iterator End = TST.end();
2105 // If there are no type names, exit early.
2106 if (I == End) return;
2108 // Print out forward declarations for structure types before anything else!
2109 Out << "/* Structure forward decls */\n";
2110 for (; I != End; ++I) {
2111 std::string Name = "struct " + CBEMangle("l_"+I->first);
2112 Out << Name << ";\n";
2113 TypeNames.insert(std::make_pair(I->second, Name));
2118 // Now we can print out typedefs. Above, we guaranteed that this can only be
2119 // for struct or opaque types.
2120 Out << "/* Typedefs */\n";
2121 for (I = TST.begin(); I != End; ++I) {
2122 std::string Name = CBEMangle("l_"+I->first);
2124 printType(Out, I->second, false, Name);
2130 // Keep track of which structures have been printed so far...
2131 std::set<const Type *> StructPrinted;
2133 // Loop over all structures then push them into the stack so they are
2134 // printed in the correct order.
2136 Out << "/* Structure contents */\n";
2137 for (I = TST.begin(); I != End; ++I)
2138 if (I->second->isStructTy() || I->second->isArrayTy())
2139 // Only print out used types!
2140 printContainedStructs(I->second, StructPrinted);
2143 // Push the struct onto the stack and recursively push all structs
2144 // this one depends on.
2146 // TODO: Make this work properly with vector types
2148 void CWriter::printContainedStructs(const Type *Ty,
2149 std::set<const Type*> &StructPrinted) {
2150 // Don't walk through pointers.
2151 if (Ty->isPointerTy() || Ty->isPrimitiveType() || Ty->isIntegerTy())
2154 // Print all contained types first.
2155 for (Type::subtype_iterator I = Ty->subtype_begin(),
2156 E = Ty->subtype_end(); I != E; ++I)
2157 printContainedStructs(*I, StructPrinted);
2159 if (Ty->isStructTy() || Ty->isArrayTy()) {
2160 // Check to see if we have already printed this struct.
2161 if (StructPrinted.insert(Ty).second) {
2162 // Print structure type out.
2163 std::string Name = TypeNames[Ty];
2164 printType(Out, Ty, false, Name, true);
2170 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
2171 /// isStructReturn - Should this function actually return a struct by-value?
2172 bool isStructReturn = F->hasStructRetAttr();
2174 if (F->hasLocalLinkage()) Out << "static ";
2175 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
2176 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
2177 switch (F->getCallingConv()) {
2178 case CallingConv::X86_StdCall:
2179 Out << "__attribute__((stdcall)) ";
2181 case CallingConv::X86_FastCall:
2182 Out << "__attribute__((fastcall)) ";
2184 case CallingConv::X86_ThisCall:
2185 Out << "__attribute__((thiscall)) ";
2191 // Loop over the arguments, printing them...
2192 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
2193 const AttrListPtr &PAL = F->getAttributes();
2196 raw_string_ostream FunctionInnards(tstr);
2198 // Print out the name...
2199 FunctionInnards << GetValueName(F) << '(';
2201 bool PrintedArg = false;
2202 if (!F->isDeclaration()) {
2203 if (!F->arg_empty()) {
2204 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2207 // If this is a struct-return function, don't print the hidden
2208 // struct-return argument.
2209 if (isStructReturn) {
2210 assert(I != E && "Invalid struct return function!");
2215 std::string ArgName;
2216 for (; I != E; ++I) {
2217 if (PrintedArg) FunctionInnards << ", ";
2218 if (I->hasName() || !Prototype)
2219 ArgName = GetValueName(I);
2222 const Type *ArgTy = I->getType();
2223 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2224 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2225 ByValParams.insert(I);
2227 printType(FunctionInnards, ArgTy,
2228 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
2235 // Loop over the arguments, printing them.
2236 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2239 // If this is a struct-return function, don't print the hidden
2240 // struct-return argument.
2241 if (isStructReturn) {
2242 assert(I != E && "Invalid struct return function!");
2247 for (; I != E; ++I) {
2248 if (PrintedArg) FunctionInnards << ", ";
2249 const Type *ArgTy = *I;
2250 if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
2251 assert(ArgTy->isPointerTy());
2252 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2254 printType(FunctionInnards, ArgTy,
2255 /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
2261 if (!PrintedArg && FT->isVarArg()) {
2262 FunctionInnards << "int vararg_dummy_arg";
2266 // Finish printing arguments... if this is a vararg function, print the ...,
2267 // unless there are no known types, in which case, we just emit ().
2269 if (FT->isVarArg() && PrintedArg) {
2270 FunctionInnards << ",..."; // Output varargs portion of signature!
2271 } else if (!FT->isVarArg() && !PrintedArg) {
2272 FunctionInnards << "void"; // ret() -> ret(void) in C.
2274 FunctionInnards << ')';
2276 // Get the return tpe for the function.
2278 if (!isStructReturn)
2279 RetTy = F->getReturnType();
2281 // If this is a struct-return function, print the struct-return type.
2282 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2285 // Print out the return type and the signature built above.
2286 printType(Out, RetTy,
2287 /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
2288 FunctionInnards.str());
2291 static inline bool isFPIntBitCast(const Instruction &I) {
2292 if (!isa<BitCastInst>(I))
2294 const Type *SrcTy = I.getOperand(0)->getType();
2295 const Type *DstTy = I.getType();
2296 return (SrcTy->isFloatingPointTy() && DstTy->isIntegerTy()) ||
2297 (DstTy->isFloatingPointTy() && SrcTy->isIntegerTy());
2300 void CWriter::printFunction(Function &F) {
2301 /// isStructReturn - Should this function actually return a struct by-value?
2302 bool isStructReturn = F.hasStructRetAttr();
2304 printFunctionSignature(&F, false);
2307 // If this is a struct return function, handle the result with magic.
2308 if (isStructReturn) {
2309 const Type *StructTy =
2310 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2312 printType(Out, StructTy, false, "StructReturn");
2313 Out << "; /* Struct return temporary */\n";
2316 printType(Out, F.arg_begin()->getType(), false,
2317 GetValueName(F.arg_begin()));
2318 Out << " = &StructReturn;\n";
2321 bool PrintedVar = false;
2323 // print local variable information for the function
2324 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2325 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2327 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2328 Out << "; /* Address-exposed local */\n";
2330 } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
2331 !isInlinableInst(*I)) {
2333 printType(Out, I->getType(), false, GetValueName(&*I));
2336 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2338 printType(Out, I->getType(), false,
2339 GetValueName(&*I)+"__PHI_TEMPORARY");
2344 // We need a temporary for the BitCast to use so it can pluck a value out
2345 // of a union to do the BitCast. This is separate from the need for a
2346 // variable to hold the result of the BitCast.
2347 if (isFPIntBitCast(*I)) {
2348 Out << " llvmBitCastUnion " << GetValueName(&*I)
2349 << "__BITCAST_TEMPORARY;\n";
2357 if (F.hasExternalLinkage() && F.getName() == "main")
2358 Out << " CODE_FOR_MAIN();\n";
2360 // print the basic blocks
2361 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2362 if (Loop *L = LI->getLoopFor(BB)) {
2363 if (L->getHeader() == BB && L->getParentLoop() == 0)
2366 printBasicBlock(BB);
2373 void CWriter::printLoop(Loop *L) {
2374 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2375 << "' to make GCC happy */\n";
2376 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2377 BasicBlock *BB = L->getBlocks()[i];
2378 Loop *BBLoop = LI->getLoopFor(BB);
2380 printBasicBlock(BB);
2381 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2384 Out << " } while (1); /* end of syntactic loop '"
2385 << L->getHeader()->getName() << "' */\n";
2388 void CWriter::printBasicBlock(BasicBlock *BB) {
2390 // Don't print the label for the basic block if there are no uses, or if
2391 // the only terminator use is the predecessor basic block's terminator.
2392 // We have to scan the use list because PHI nodes use basic blocks too but
2393 // do not require a label to be generated.
2395 bool NeedsLabel = false;
2396 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2397 if (isGotoCodeNecessary(*PI, BB)) {
2402 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2404 // Output all of the instructions in the basic block...
2405 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2407 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2408 if (II->getType() != Type::getVoidTy(BB->getContext()) &&
2413 writeInstComputationInline(*II);
2418 // Don't emit prefix or suffix for the terminator.
2419 visit(*BB->getTerminator());
2423 // Specific Instruction type classes... note that all of the casts are
2424 // necessary because we use the instruction classes as opaque types...
2426 void CWriter::visitReturnInst(ReturnInst &I) {
2427 // If this is a struct return function, return the temporary struct.
2428 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2430 if (isStructReturn) {
2431 Out << " return StructReturn;\n";
2435 // Don't output a void return if this is the last basic block in the function
2436 if (I.getNumOperands() == 0 &&
2437 &*--I.getParent()->getParent()->end() == I.getParent() &&
2438 !I.getParent()->size() == 1) {
2443 if (I.getNumOperands()) {
2445 writeOperand(I.getOperand(0));
2450 void CWriter::visitSwitchInst(SwitchInst &SI) {
2453 writeOperand(SI.getOperand(0));
2454 Out << ") {\n default:\n";
2455 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2456 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2458 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2460 writeOperand(SI.getOperand(i));
2462 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2463 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2464 printBranchToBlock(SI.getParent(), Succ, 2);
2465 if (Function::iterator(Succ) == llvm::next(Function::iterator(SI.getParent())))
2471 void CWriter::visitIndirectBrInst(IndirectBrInst &IBI) {
2472 Out << " goto *(void*)(";
2473 writeOperand(IBI.getOperand(0));
2477 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2478 Out << " /*UNREACHABLE*/;\n";
2481 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2482 /// FIXME: This should be reenabled, but loop reordering safe!!
2485 if (llvm::next(Function::iterator(From)) != Function::iterator(To))
2486 return true; // Not the direct successor, we need a goto.
2488 //isa<SwitchInst>(From->getTerminator())
2490 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2495 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2496 BasicBlock *Successor,
2498 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2499 PHINode *PN = cast<PHINode>(I);
2500 // Now we have to do the printing.
2501 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2502 if (!isa<UndefValue>(IV)) {
2503 Out << std::string(Indent, ' ');
2504 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2506 Out << "; /* for PHI node */\n";
2511 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2513 if (isGotoCodeNecessary(CurBB, Succ)) {
2514 Out << std::string(Indent, ' ') << " goto ";
2520 // Branch instruction printing - Avoid printing out a branch to a basic block
2521 // that immediately succeeds the current one.
2523 void CWriter::visitBranchInst(BranchInst &I) {
2525 if (I.isConditional()) {
2526 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2528 writeOperand(I.getCondition());
2531 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2532 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2534 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2535 Out << " } else {\n";
2536 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2537 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2540 // First goto not necessary, assume second one is...
2542 writeOperand(I.getCondition());
2545 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2546 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2551 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2552 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2557 // PHI nodes get copied into temporary values at the end of predecessor basic
2558 // blocks. We now need to copy these temporary values into the REAL value for
2560 void CWriter::visitPHINode(PHINode &I) {
2562 Out << "__PHI_TEMPORARY";
2566 void CWriter::visitBinaryOperator(Instruction &I) {
2567 // binary instructions, shift instructions, setCond instructions.
2568 assert(!I.getType()->isPointerTy());
2570 // We must cast the results of binary operations which might be promoted.
2571 bool needsCast = false;
2572 if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
2573 (I.getType() == Type::getInt16Ty(I.getContext()))
2574 || (I.getType() == Type::getFloatTy(I.getContext()))) {
2577 printType(Out, I.getType(), false);
2581 // If this is a negation operation, print it out as such. For FP, we don't
2582 // want to print "-0.0 - X".
2583 if (BinaryOperator::isNeg(&I)) {
2585 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2587 } else if (BinaryOperator::isFNeg(&I)) {
2589 writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
2591 } else if (I.getOpcode() == Instruction::FRem) {
2592 // Output a call to fmod/fmodf instead of emitting a%b
2593 if (I.getType() == Type::getFloatTy(I.getContext()))
2595 else if (I.getType() == Type::getDoubleTy(I.getContext()))
2597 else // all 3 flavors of long double
2599 writeOperand(I.getOperand(0));
2601 writeOperand(I.getOperand(1));
2605 // Write out the cast of the instruction's value back to the proper type
2607 bool NeedsClosingParens = writeInstructionCast(I);
2609 // Certain instructions require the operand to be forced to a specific type
2610 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2611 // below for operand 1
2612 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2614 switch (I.getOpcode()) {
2615 case Instruction::Add:
2616 case Instruction::FAdd: Out << " + "; break;
2617 case Instruction::Sub:
2618 case Instruction::FSub: Out << " - "; break;
2619 case Instruction::Mul:
2620 case Instruction::FMul: Out << " * "; break;
2621 case Instruction::URem:
2622 case Instruction::SRem:
2623 case Instruction::FRem: Out << " % "; break;
2624 case Instruction::UDiv:
2625 case Instruction::SDiv:
2626 case Instruction::FDiv: Out << " / "; break;
2627 case Instruction::And: Out << " & "; break;
2628 case Instruction::Or: Out << " | "; break;
2629 case Instruction::Xor: Out << " ^ "; break;
2630 case Instruction::Shl : Out << " << "; break;
2631 case Instruction::LShr:
2632 case Instruction::AShr: Out << " >> "; break;
2635 errs() << "Invalid operator type!" << I;
2637 llvm_unreachable(0);
2640 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2641 if (NeedsClosingParens)
2650 void CWriter::visitICmpInst(ICmpInst &I) {
2651 // We must cast the results of icmp which might be promoted.
2652 bool needsCast = false;
2654 // Write out the cast of the instruction's value back to the proper type
2656 bool NeedsClosingParens = writeInstructionCast(I);
2658 // Certain icmp predicate require the operand to be forced to a specific type
2659 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2660 // below for operand 1
2661 writeOperandWithCast(I.getOperand(0), I);
2663 switch (I.getPredicate()) {
2664 case ICmpInst::ICMP_EQ: Out << " == "; break;
2665 case ICmpInst::ICMP_NE: Out << " != "; break;
2666 case ICmpInst::ICMP_ULE:
2667 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2668 case ICmpInst::ICMP_UGE:
2669 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2670 case ICmpInst::ICMP_ULT:
2671 case ICmpInst::ICMP_SLT: Out << " < "; break;
2672 case ICmpInst::ICMP_UGT:
2673 case ICmpInst::ICMP_SGT: Out << " > "; break;
2676 errs() << "Invalid icmp predicate!" << I;
2678 llvm_unreachable(0);
2681 writeOperandWithCast(I.getOperand(1), I);
2682 if (NeedsClosingParens)
2690 void CWriter::visitFCmpInst(FCmpInst &I) {
2691 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2695 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2701 switch (I.getPredicate()) {
2702 default: llvm_unreachable("Illegal FCmp predicate");
2703 case FCmpInst::FCMP_ORD: op = "ord"; break;
2704 case FCmpInst::FCMP_UNO: op = "uno"; break;
2705 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2706 case FCmpInst::FCMP_UNE: op = "une"; break;
2707 case FCmpInst::FCMP_ULT: op = "ult"; break;
2708 case FCmpInst::FCMP_ULE: op = "ule"; break;
2709 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2710 case FCmpInst::FCMP_UGE: op = "uge"; break;
2711 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2712 case FCmpInst::FCMP_ONE: op = "one"; break;
2713 case FCmpInst::FCMP_OLT: op = "olt"; break;
2714 case FCmpInst::FCMP_OLE: op = "ole"; break;
2715 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2716 case FCmpInst::FCMP_OGE: op = "oge"; break;
2719 Out << "llvm_fcmp_" << op << "(";
2720 // Write the first operand
2721 writeOperand(I.getOperand(0));
2723 // Write the second operand
2724 writeOperand(I.getOperand(1));
2728 static const char * getFloatBitCastField(const Type *Ty) {
2729 switch (Ty->getTypeID()) {
2730 default: llvm_unreachable("Invalid Type");
2731 case Type::FloatTyID: return "Float";
2732 case Type::DoubleTyID: return "Double";
2733 case Type::IntegerTyID: {
2734 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2743 void CWriter::visitCastInst(CastInst &I) {
2744 const Type *DstTy = I.getType();
2745 const Type *SrcTy = I.getOperand(0)->getType();
2746 if (isFPIntBitCast(I)) {
2748 // These int<->float and long<->double casts need to be handled specially
2749 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2750 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2751 writeOperand(I.getOperand(0));
2752 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2753 << getFloatBitCastField(I.getType());
2759 printCast(I.getOpcode(), SrcTy, DstTy);
2761 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2762 if (SrcTy == Type::getInt1Ty(I.getContext()) &&
2763 I.getOpcode() == Instruction::SExt)
2766 writeOperand(I.getOperand(0));
2768 if (DstTy == Type::getInt1Ty(I.getContext()) &&
2769 (I.getOpcode() == Instruction::Trunc ||
2770 I.getOpcode() == Instruction::FPToUI ||
2771 I.getOpcode() == Instruction::FPToSI ||
2772 I.getOpcode() == Instruction::PtrToInt)) {
2773 // Make sure we really get a trunc to bool by anding the operand with 1
2779 void CWriter::visitSelectInst(SelectInst &I) {
2781 writeOperand(I.getCondition());
2783 writeOperand(I.getTrueValue());
2785 writeOperand(I.getFalseValue());
2790 void CWriter::lowerIntrinsics(Function &F) {
2791 // This is used to keep track of intrinsics that get generated to a lowered
2792 // function. We must generate the prototypes before the function body which
2793 // will only be expanded on first use (by the loop below).
2794 std::vector<Function*> prototypesToGen;
2796 // Examine all the instructions in this function to find the intrinsics that
2797 // need to be lowered.
2798 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2799 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2800 if (CallInst *CI = dyn_cast<CallInst>(I++))
2801 if (Function *F = CI->getCalledFunction())
2802 switch (F->getIntrinsicID()) {
2803 case Intrinsic::not_intrinsic:
2804 case Intrinsic::memory_barrier:
2805 case Intrinsic::vastart:
2806 case Intrinsic::vacopy:
2807 case Intrinsic::vaend:
2808 case Intrinsic::returnaddress:
2809 case Intrinsic::frameaddress:
2810 case Intrinsic::setjmp:
2811 case Intrinsic::longjmp:
2812 case Intrinsic::prefetch:
2813 case Intrinsic::powi:
2814 case Intrinsic::x86_sse_cmp_ss:
2815 case Intrinsic::x86_sse_cmp_ps:
2816 case Intrinsic::x86_sse2_cmp_sd:
2817 case Intrinsic::x86_sse2_cmp_pd:
2818 case Intrinsic::ppc_altivec_lvsl:
2819 // We directly implement these intrinsics
2822 // If this is an intrinsic that directly corresponds to a GCC
2823 // builtin, we handle it.
2824 const char *BuiltinName = "";
2825 #define GET_GCC_BUILTIN_NAME
2826 #include "llvm/Intrinsics.gen"
2827 #undef GET_GCC_BUILTIN_NAME
2828 // If we handle it, don't lower it.
2829 if (BuiltinName[0]) break;
2831 // All other intrinsic calls we must lower.
2832 Instruction *Before = 0;
2833 if (CI != &BB->front())
2834 Before = prior(BasicBlock::iterator(CI));
2836 IL->LowerIntrinsicCall(CI);
2837 if (Before) { // Move iterator to instruction after call
2842 // If the intrinsic got lowered to another call, and that call has
2843 // a definition then we need to make sure its prototype is emitted
2844 // before any calls to it.
2845 if (CallInst *Call = dyn_cast<CallInst>(I))
2846 if (Function *NewF = Call->getCalledFunction())
2847 if (!NewF->isDeclaration())
2848 prototypesToGen.push_back(NewF);
2853 // We may have collected some prototypes to emit in the loop above.
2854 // Emit them now, before the function that uses them is emitted. But,
2855 // be careful not to emit them twice.
2856 std::vector<Function*>::iterator I = prototypesToGen.begin();
2857 std::vector<Function*>::iterator E = prototypesToGen.end();
2858 for ( ; I != E; ++I) {
2859 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2861 printFunctionSignature(*I, true);
2867 void CWriter::visitCallInst(CallInst &I) {
2868 if (isa<InlineAsm>(I.getCalledValue()))
2869 return visitInlineAsm(I);
2871 bool WroteCallee = false;
2873 // Handle intrinsic function calls first...
2874 if (Function *F = I.getCalledFunction())
2875 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2876 if (visitBuiltinCall(I, ID, WroteCallee))
2879 Value *Callee = I.getCalledValue();
2881 const PointerType *PTy = cast<PointerType>(Callee->getType());
2882 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2884 // If this is a call to a struct-return function, assign to the first
2885 // parameter instead of passing it to the call.
2886 const AttrListPtr &PAL = I.getAttributes();
2887 bool hasByVal = I.hasByValArgument();
2888 bool isStructRet = I.hasStructRetAttr();
2890 writeOperandDeref(I.getArgOperand(0));
2894 if (I.isTailCall()) Out << " /*tail*/ ";
2897 // If this is an indirect call to a struct return function, we need to cast
2898 // the pointer. Ditto for indirect calls with byval arguments.
2899 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2901 // GCC is a real PITA. It does not permit codegening casts of functions to
2902 // function pointers if they are in a call (it generates a trap instruction
2903 // instead!). We work around this by inserting a cast to void* in between
2904 // the function and the function pointer cast. Unfortunately, we can't just
2905 // form the constant expression here, because the folder will immediately
2908 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2909 // that void* and function pointers have the same size. :( To deal with this
2910 // in the common case, we handle casts where the number of arguments passed
2913 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2915 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2921 // Ok, just cast the pointer type.
2924 printStructReturnPointerFunctionType(Out, PAL,
2925 cast<PointerType>(I.getCalledValue()->getType()));
2927 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2929 printType(Out, I.getCalledValue()->getType());
2932 writeOperand(Callee);
2933 if (NeedsCast) Out << ')';
2938 bool PrintedArg = false;
2939 if(FTy->isVarArg() && !FTy->getNumParams()) {
2940 Out << "0 /*dummy arg*/";
2944 unsigned NumDeclaredParams = FTy->getNumParams();
2946 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
2948 if (isStructRet) { // Skip struct return argument.
2954 for (; AI != AE; ++AI, ++ArgNo) {
2955 if (PrintedArg) Out << ", ";
2956 if (ArgNo < NumDeclaredParams &&
2957 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2959 printType(Out, FTy->getParamType(ArgNo),
2960 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
2963 // Check if the argument is expected to be passed by value.
2964 if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
2965 writeOperandDeref(*AI);
2973 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
2974 /// if the entire call is handled, return false if it wasn't handled, and
2975 /// optionally set 'WroteCallee' if the callee has already been printed out.
2976 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
2977 bool &WroteCallee) {
2980 // If this is an intrinsic that directly corresponds to a GCC
2981 // builtin, we emit it here.
2982 const char *BuiltinName = "";
2983 Function *F = I.getCalledFunction();
2984 #define GET_GCC_BUILTIN_NAME
2985 #include "llvm/Intrinsics.gen"
2986 #undef GET_GCC_BUILTIN_NAME
2987 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2993 case Intrinsic::memory_barrier:
2994 Out << "__sync_synchronize()";
2996 case Intrinsic::vastart:
2999 Out << "va_start(*(va_list*)";
3000 writeOperand(I.getArgOperand(0));
3002 // Output the last argument to the enclosing function.
3003 if (I.getParent()->getParent()->arg_empty())
3004 Out << "vararg_dummy_arg";
3006 writeOperand(--I.getParent()->getParent()->arg_end());
3009 case Intrinsic::vaend:
3010 if (!isa<ConstantPointerNull>(I.getArgOperand(0))) {
3011 Out << "0; va_end(*(va_list*)";
3012 writeOperand(I.getArgOperand(0));
3015 Out << "va_end(*(va_list*)0)";
3018 case Intrinsic::vacopy:
3020 Out << "va_copy(*(va_list*)";
3021 writeOperand(I.getArgOperand(0));
3022 Out << ", *(va_list*)";
3023 writeOperand(I.getArgOperand(1));
3026 case Intrinsic::returnaddress:
3027 Out << "__builtin_return_address(";
3028 writeOperand(I.getArgOperand(0));
3031 case Intrinsic::frameaddress:
3032 Out << "__builtin_frame_address(";
3033 writeOperand(I.getArgOperand(0));
3036 case Intrinsic::powi:
3037 Out << "__builtin_powi(";
3038 writeOperand(I.getArgOperand(0));
3040 writeOperand(I.getArgOperand(1));
3043 case Intrinsic::setjmp:
3044 Out << "setjmp(*(jmp_buf*)";
3045 writeOperand(I.getArgOperand(0));
3048 case Intrinsic::longjmp:
3049 Out << "longjmp(*(jmp_buf*)";
3050 writeOperand(I.getArgOperand(0));
3052 writeOperand(I.getArgOperand(1));
3055 case Intrinsic::prefetch:
3056 Out << "LLVM_PREFETCH((const void *)";
3057 writeOperand(I.getArgOperand(0));
3059 writeOperand(I.getArgOperand(1));
3061 writeOperand(I.getArgOperand(2));
3064 case Intrinsic::stacksave:
3065 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
3066 // to work around GCC bugs (see PR1809).
3067 Out << "0; *((void**)&" << GetValueName(&I)
3068 << ") = __builtin_stack_save()";
3070 case Intrinsic::x86_sse_cmp_ss:
3071 case Intrinsic::x86_sse_cmp_ps:
3072 case Intrinsic::x86_sse2_cmp_sd:
3073 case Intrinsic::x86_sse2_cmp_pd:
3075 printType(Out, I.getType());
3077 // Multiple GCC builtins multiplex onto this intrinsic.
3078 switch (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()) {
3079 default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
3080 case 0: Out << "__builtin_ia32_cmpeq"; break;
3081 case 1: Out << "__builtin_ia32_cmplt"; break;
3082 case 2: Out << "__builtin_ia32_cmple"; break;
3083 case 3: Out << "__builtin_ia32_cmpunord"; break;
3084 case 4: Out << "__builtin_ia32_cmpneq"; break;
3085 case 5: Out << "__builtin_ia32_cmpnlt"; break;
3086 case 6: Out << "__builtin_ia32_cmpnle"; break;
3087 case 7: Out << "__builtin_ia32_cmpord"; break;
3089 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
3093 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
3099 writeOperand(I.getArgOperand(0));
3101 writeOperand(I.getArgOperand(1));
3104 case Intrinsic::ppc_altivec_lvsl:
3106 printType(Out, I.getType());
3108 Out << "__builtin_altivec_lvsl(0, (void*)";
3109 writeOperand(I.getArgOperand(0));
3115 //This converts the llvm constraint string to something gcc is expecting.
3116 //TODO: work out platform independent constraints and factor those out
3117 // of the per target tables
3118 // handle multiple constraint codes
3119 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
3120 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
3122 // Grab the translation table from MCAsmInfo if it exists.
3123 const MCAsmInfo *TargetAsm;
3124 std::string Triple = TheModule->getTargetTriple();
3126 Triple = llvm::sys::getHostTriple();
3129 if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
3130 TargetAsm = Match->createAsmInfo(Triple);
3134 const char *const *table = TargetAsm->getAsmCBE();
3136 // Search the translation table if it exists.
3137 for (int i = 0; table && table[i]; i += 2)
3138 if (c.Codes[0] == table[i]) {
3143 // Default is identity.
3148 //TODO: import logic from AsmPrinter.cpp
3149 static std::string gccifyAsm(std::string asmstr) {
3150 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
3151 if (asmstr[i] == '\n')
3152 asmstr.replace(i, 1, "\\n");
3153 else if (asmstr[i] == '\t')
3154 asmstr.replace(i, 1, "\\t");
3155 else if (asmstr[i] == '$') {
3156 if (asmstr[i + 1] == '{') {
3157 std::string::size_type a = asmstr.find_first_of(':', i + 1);
3158 std::string::size_type b = asmstr.find_first_of('}', i + 1);
3159 std::string n = "%" +
3160 asmstr.substr(a + 1, b - a - 1) +
3161 asmstr.substr(i + 2, a - i - 2);
3162 asmstr.replace(i, b - i + 1, n);
3165 asmstr.replace(i, 1, "%");
3167 else if (asmstr[i] == '%')//grr
3168 { asmstr.replace(i, 1, "%%"); ++i;}
3173 //TODO: assumptions about what consume arguments from the call are likely wrong
3174 // handle communitivity
3175 void CWriter::visitInlineAsm(CallInst &CI) {
3176 InlineAsm* as = cast<InlineAsm>(CI.getCalledValue());
3177 InlineAsm::ConstraintInfoVector Constraints = as->ParseConstraints();
3179 std::vector<std::pair<Value*, int> > ResultVals;
3180 if (CI.getType() == Type::getVoidTy(CI.getContext()))
3182 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
3183 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
3184 ResultVals.push_back(std::make_pair(&CI, (int)i));
3186 ResultVals.push_back(std::make_pair(&CI, -1));
3189 // Fix up the asm string for gcc and emit it.
3190 Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
3193 unsigned ValueCount = 0;
3194 bool IsFirst = true;
3196 // Convert over all the output constraints.
3197 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3198 E = Constraints.end(); I != E; ++I) {
3200 if (I->Type != InlineAsm::isOutput) {
3202 continue; // Ignore non-output constraints.
3205 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3206 std::string C = InterpretASMConstraint(*I);
3207 if (C.empty()) continue;
3218 if (ValueCount < ResultVals.size()) {
3219 DestVal = ResultVals[ValueCount].first;
3220 DestValNo = ResultVals[ValueCount].second;
3222 DestVal = CI.getArgOperand(ValueCount-ResultVals.size());
3224 if (I->isEarlyClobber)
3227 Out << "\"=" << C << "\"(" << GetValueName(DestVal);
3228 if (DestValNo != -1)
3229 Out << ".field" << DestValNo; // Multiple retvals.
3235 // Convert over all the input constraints.
3239 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3240 E = Constraints.end(); I != E; ++I) {
3241 if (I->Type != InlineAsm::isInput) {
3243 continue; // Ignore non-input constraints.
3246 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3247 std::string C = InterpretASMConstraint(*I);
3248 if (C.empty()) continue;
3255 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
3256 Value *SrcVal = CI.getArgOperand(ValueCount-ResultVals.size());
3258 Out << "\"" << C << "\"(";
3260 writeOperand(SrcVal);
3262 writeOperandDeref(SrcVal);
3266 // Convert over the clobber constraints.
3268 for (InlineAsm::ConstraintInfoVector::iterator I = Constraints.begin(),
3269 E = Constraints.end(); I != E; ++I) {
3270 if (I->Type != InlineAsm::isClobber)
3271 continue; // Ignore non-input constraints.
3273 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
3274 std::string C = InterpretASMConstraint(*I);
3275 if (C.empty()) continue;
3282 Out << '\"' << C << '"';
3288 void CWriter::visitAllocaInst(AllocaInst &I) {
3290 printType(Out, I.getType());
3291 Out << ") alloca(sizeof(";
3292 printType(Out, I.getType()->getElementType());
3294 if (I.isArrayAllocation()) {
3296 writeOperand(I.getOperand(0));
3301 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3302 gep_type_iterator E, bool Static) {
3304 // If there are no indices, just print out the pointer.
3310 // Find out if the last index is into a vector. If so, we have to print this
3311 // specially. Since vectors can't have elements of indexable type, only the
3312 // last index could possibly be of a vector element.
3313 const VectorType *LastIndexIsVector = 0;
3315 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3316 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3321 // If the last index is into a vector, we can't print it as &a[i][j] because
3322 // we can't index into a vector with j in GCC. Instead, emit this as
3323 // (((float*)&a[i])+j)
3324 if (LastIndexIsVector) {
3326 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3332 // If the first index is 0 (very typical) we can do a number of
3333 // simplifications to clean up the code.
3334 Value *FirstOp = I.getOperand();
3335 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3336 // First index isn't simple, print it the hard way.
3339 ++I; // Skip the zero index.
3341 // Okay, emit the first operand. If Ptr is something that is already address
3342 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3343 if (isAddressExposed(Ptr)) {
3344 writeOperandInternal(Ptr, Static);
3345 } else if (I != E && (*I)->isStructTy()) {
3346 // If we didn't already emit the first operand, see if we can print it as
3347 // P->f instead of "P[0].f"
3349 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3350 ++I; // eat the struct index as well.
3352 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3359 for (; I != E; ++I) {
3360 if ((*I)->isStructTy()) {
3361 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3362 } else if ((*I)->isArrayTy()) {
3364 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3366 } else if (!(*I)->isVectorTy()) {
3368 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3371 // If the last index is into a vector, then print it out as "+j)". This
3372 // works with the 'LastIndexIsVector' code above.
3373 if (isa<Constant>(I.getOperand()) &&
3374 cast<Constant>(I.getOperand())->isNullValue()) {
3375 Out << "))"; // avoid "+0".
3378 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3386 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3387 bool IsVolatile, unsigned Alignment) {
3389 bool IsUnaligned = Alignment &&
3390 Alignment < TD->getABITypeAlignment(OperandType);
3394 if (IsVolatile || IsUnaligned) {
3397 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3398 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3401 if (IsVolatile) Out << "volatile ";
3407 writeOperand(Operand);
3409 if (IsVolatile || IsUnaligned) {
3416 void CWriter::visitLoadInst(LoadInst &I) {
3417 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3422 void CWriter::visitStoreInst(StoreInst &I) {
3423 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3424 I.isVolatile(), I.getAlignment());
3426 Value *Operand = I.getOperand(0);
3427 Constant *BitMask = 0;
3428 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3429 if (!ITy->isPowerOf2ByteWidth())
3430 // We have a bit width that doesn't match an even power-of-2 byte
3431 // size. Consequently we must & the value with the type's bit mask
3432 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3435 writeOperand(Operand);
3438 printConstant(BitMask, false);
3443 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3444 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3445 gep_type_end(I), false);
3448 void CWriter::visitVAArgInst(VAArgInst &I) {
3449 Out << "va_arg(*(va_list*)";
3450 writeOperand(I.getOperand(0));
3452 printType(Out, I.getType());
3456 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3457 const Type *EltTy = I.getType()->getElementType();
3458 writeOperand(I.getOperand(0));
3461 printType(Out, PointerType::getUnqual(EltTy));
3462 Out << ")(&" << GetValueName(&I) << "))[";
3463 writeOperand(I.getOperand(2));
3465 writeOperand(I.getOperand(1));
3469 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3470 // We know that our operand is not inlined.
3473 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3474 printType(Out, PointerType::getUnqual(EltTy));
3475 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3476 writeOperand(I.getOperand(1));
3480 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3482 printType(Out, SVI.getType());
3484 const VectorType *VT = SVI.getType();
3485 unsigned NumElts = VT->getNumElements();
3486 const Type *EltTy = VT->getElementType();
3488 for (unsigned i = 0; i != NumElts; ++i) {
3490 int SrcVal = SVI.getMaskValue(i);
3491 if ((unsigned)SrcVal >= NumElts*2) {
3492 Out << " 0/*undef*/ ";
3494 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3495 if (isa<Instruction>(Op)) {
3496 // Do an extractelement of this value from the appropriate input.
3498 printType(Out, PointerType::getUnqual(EltTy));
3499 Out << ")(&" << GetValueName(Op)
3500 << "))[" << (SrcVal & (NumElts-1)) << "]";
3501 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3504 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3513 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
3514 // Start by copying the entire aggregate value into the result variable.
3515 writeOperand(IVI.getOperand(0));
3518 // Then do the insert to update the field.
3519 Out << GetValueName(&IVI);
3520 for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
3522 const Type *IndexedTy =
3523 ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
3524 if (IndexedTy->isArrayTy())
3525 Out << ".array[" << *i << "]";
3527 Out << ".field" << *i;
3530 writeOperand(IVI.getOperand(1));
3533 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
3535 if (isa<UndefValue>(EVI.getOperand(0))) {
3537 printType(Out, EVI.getType());
3538 Out << ") 0/*UNDEF*/";
3540 Out << GetValueName(EVI.getOperand(0));
3541 for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
3543 const Type *IndexedTy =
3544 ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
3545 if (IndexedTy->isArrayTy())
3546 Out << ".array[" << *i << "]";
3548 Out << ".field" << *i;
3554 //===----------------------------------------------------------------------===//
3555 // External Interface declaration
3556 //===----------------------------------------------------------------------===//
3558 bool CTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
3559 formatted_raw_ostream &o,
3560 CodeGenFileType FileType,
3561 CodeGenOpt::Level OptLevel,
3562 bool DisableVerify) {
3563 if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
3565 PM.add(createGCLoweringPass());
3566 PM.add(createLowerInvokePass());
3567 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3568 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3569 PM.add(new CWriter(o));
3570 PM.add(createGCInfoDeleter());