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/Analysis/ConstantsScanner.h"
28 #include "llvm/Analysis/FindUsedTypes.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "llvm/Target/TargetMachineRegistry.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Support/CallSite.h"
37 #include "llvm/Support/CFG.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/InstVisitor.h"
40 #include "llvm/Support/Mangler.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Config/config.h"
50 // Register the target.
51 static RegisterTarget<CTargetMachine> X("c", " C backend");
54 /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
55 /// any unnamed structure types that are used by the program, and merges
56 /// external functions with the same name.
58 class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
61 CBackendNameAllUsedStructsAndMergeFunctions()
62 : ModulePass((intptr_t)&ID) {}
63 void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addRequired<FindUsedTypes>();
67 virtual const char *getPassName() const {
68 return "C backend type canonicalizer";
71 virtual bool runOnModule(Module &M);
74 char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
76 /// CWriter - This class is the main chunk of code that converts an LLVM
77 /// module to a C translation unit.
78 class CWriter : public FunctionPass, public InstVisitor<CWriter> {
80 IntrinsicLowering *IL;
83 const Module *TheModule;
84 const TargetAsmInfo* TAsm;
86 std::map<const Type *, std::string> TypeNames;
87 std::map<const ConstantFP *, unsigned> FPConstantMap;
88 std::set<Function*> intrinsicPrototypesAlreadyGenerated;
89 std::set<const Argument*> ByValParams;
93 explicit CWriter(std::ostream &o)
94 : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0),
95 TheModule(0), TAsm(0), TD(0) {}
97 virtual const char *getPassName() const { return "C backend"; }
99 void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<LoopInfo>();
101 AU.setPreservesAll();
104 virtual bool doInitialization(Module &M);
106 bool runOnFunction(Function &F) {
107 LI = &getAnalysis<LoopInfo>();
109 // Get rid of intrinsics we can't handle.
112 // Output all floating point constants that cannot be printed accurately.
113 printFloatingPointConstants(F);
119 virtual bool doFinalization(Module &M) {
122 FPConstantMap.clear();
125 intrinsicPrototypesAlreadyGenerated.clear();
129 std::ostream &printType(std::ostream &Out, const Type *Ty,
130 bool isSigned = false,
131 const std::string &VariableName = "",
132 bool IgnoreName = false,
133 const PAListPtr &PAL = PAListPtr());
134 std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
136 const std::string &NameSoFar = "");
138 void printStructReturnPointerFunctionType(std::ostream &Out,
139 const PAListPtr &PAL,
140 const PointerType *Ty);
142 /// writeOperandDeref - Print the result of dereferencing the specified
143 /// operand with '*'. This is equivalent to printing '*' then using
144 /// writeOperand, but avoids excess syntax in some cases.
145 void writeOperandDeref(Value *Operand) {
146 if (isAddressExposed(Operand)) {
147 // Already something with an address exposed.
148 writeOperandInternal(Operand);
151 writeOperand(Operand);
156 void writeOperand(Value *Operand);
157 void writeOperandRaw(Value *Operand);
158 void writeInstComputationInline(Instruction &I);
159 void writeOperandInternal(Value *Operand);
160 void writeOperandWithCast(Value* Operand, unsigned Opcode);
161 void writeOperandWithCast(Value* Operand, const ICmpInst &I);
162 bool writeInstructionCast(const Instruction &I);
164 void writeMemoryAccess(Value *Operand, const Type *OperandType,
165 bool IsVolatile, unsigned Alignment);
168 std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
170 void lowerIntrinsics(Function &F);
172 void printModule(Module *M);
173 void printModuleTypes(const TypeSymbolTable &ST);
174 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
175 void printFloatingPointConstants(Function &F);
176 void printFunctionSignature(const Function *F, bool Prototype);
178 void printFunction(Function &);
179 void printBasicBlock(BasicBlock *BB);
180 void printLoop(Loop *L);
182 void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
183 void printConstant(Constant *CPV);
184 void printConstantWithCast(Constant *CPV, unsigned Opcode);
185 bool printConstExprCast(const ConstantExpr *CE);
186 void printConstantArray(ConstantArray *CPA);
187 void printConstantVector(ConstantVector *CV);
189 /// isAddressExposed - Return true if the specified value's name needs to
190 /// have its address taken in order to get a C value of the correct type.
191 /// This happens for global variables, byval parameters, and direct allocas.
192 bool isAddressExposed(const Value *V) const {
193 if (const Argument *A = dyn_cast<Argument>(V))
194 return ByValParams.count(A);
195 return isa<GlobalVariable>(V) || isDirectAlloca(V);
198 // isInlinableInst - Attempt to inline instructions into their uses to build
199 // trees as much as possible. To do this, we have to consistently decide
200 // what is acceptable to inline, so that variable declarations don't get
201 // printed and an extra copy of the expr is not emitted.
203 static bool isInlinableInst(const Instruction &I) {
204 // Always inline cmp instructions, even if they are shared by multiple
205 // expressions. GCC generates horrible code if we don't.
209 // Must be an expression, must be used exactly once. If it is dead, we
210 // emit it inline where it would go.
211 if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
212 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
213 isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I))
214 // Don't inline a load across a store or other bad things!
217 // Must not be used in inline asm, extractelement, or shufflevector.
219 const Instruction &User = cast<Instruction>(*I.use_back());
220 if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
221 isa<ShuffleVectorInst>(User))
225 // Only inline instruction it if it's use is in the same BB as the inst.
226 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
229 // isDirectAlloca - Define fixed sized allocas in the entry block as direct
230 // variables which are accessed with the & operator. This causes GCC to
231 // generate significantly better code than to emit alloca calls directly.
233 static const AllocaInst *isDirectAlloca(const Value *V) {
234 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
235 if (!AI) return false;
236 if (AI->isArrayAllocation())
237 return 0; // FIXME: we can also inline fixed size array allocas!
238 if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
243 // isInlineAsm - Check if the instruction is a call to an inline asm chunk
244 static bool isInlineAsm(const Instruction& I) {
245 if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
250 // Instruction visitation functions
251 friend class InstVisitor<CWriter>;
253 void visitReturnInst(ReturnInst &I);
254 void visitBranchInst(BranchInst &I);
255 void visitSwitchInst(SwitchInst &I);
256 void visitInvokeInst(InvokeInst &I) {
257 assert(0 && "Lowerinvoke pass didn't work!");
260 void visitUnwindInst(UnwindInst &I) {
261 assert(0 && "Lowerinvoke pass didn't work!");
263 void visitUnreachableInst(UnreachableInst &I);
265 void visitPHINode(PHINode &I);
266 void visitBinaryOperator(Instruction &I);
267 void visitICmpInst(ICmpInst &I);
268 void visitFCmpInst(FCmpInst &I);
270 void visitCastInst (CastInst &I);
271 void visitSelectInst(SelectInst &I);
272 void visitCallInst (CallInst &I);
273 void visitInlineAsm(CallInst &I);
274 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
276 void visitMallocInst(MallocInst &I);
277 void visitAllocaInst(AllocaInst &I);
278 void visitFreeInst (FreeInst &I);
279 void visitLoadInst (LoadInst &I);
280 void visitStoreInst (StoreInst &I);
281 void visitGetElementPtrInst(GetElementPtrInst &I);
282 void visitVAArgInst (VAArgInst &I);
284 void visitInsertElementInst(InsertElementInst &I);
285 void visitExtractElementInst(ExtractElementInst &I);
286 void visitShuffleVectorInst(ShuffleVectorInst &SVI);
287 void visitGetResultInst(GetResultInst &GRI);
289 void visitInstruction(Instruction &I) {
290 cerr << "C Writer does not know about " << I;
294 void outputLValue(Instruction *I) {
295 Out << " " << GetValueName(I) << " = ";
298 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
299 void printPHICopiesForSuccessor(BasicBlock *CurBlock,
300 BasicBlock *Successor, unsigned Indent);
301 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
303 void printGEPExpression(Value *Ptr, gep_type_iterator I,
304 gep_type_iterator E);
306 std::string GetValueName(const Value *Operand);
310 char CWriter::ID = 0;
312 /// This method inserts names for any unnamed structure types that are used by
313 /// the program, and removes names from structure types that are not used by the
316 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
317 // Get a set of types that are used by the program...
318 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
320 // Loop over the module symbol table, removing types from UT that are
321 // already named, and removing names for types that are not used.
323 TypeSymbolTable &TST = M.getTypeSymbolTable();
324 for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
326 TypeSymbolTable::iterator I = TI++;
328 // If this isn't a struct type, remove it from our set of types to name.
329 // This simplifies emission later.
330 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
333 // If this is not used, remove it from the symbol table.
334 std::set<const Type *>::iterator UTI = UT.find(I->second);
338 UT.erase(UTI); // Only keep one name for this type.
342 // UT now contains types that are not named. Loop over it, naming
345 bool Changed = false;
346 unsigned RenameCounter = 0;
347 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
349 if (const StructType *ST = dyn_cast<StructType>(*I)) {
350 while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
356 // Loop over all external functions and globals. If we have two with
357 // identical names, merge them.
358 // FIXME: This code should disappear when we don't allow values with the same
359 // names when they have different types!
360 std::map<std::string, GlobalValue*> ExtSymbols;
361 for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
363 if (GV->isDeclaration() && GV->hasName()) {
364 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
365 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
367 // Found a conflict, replace this global with the previous one.
368 GlobalValue *OldGV = X.first->second;
369 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
370 GV->eraseFromParent();
375 // Do the same for globals.
376 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
378 GlobalVariable *GV = I++;
379 if (GV->isDeclaration() && GV->hasName()) {
380 std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
381 = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
383 // Found a conflict, replace this global with the previous one.
384 GlobalValue *OldGV = X.first->second;
385 GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
386 GV->eraseFromParent();
395 /// printStructReturnPointerFunctionType - This is like printType for a struct
396 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
397 /// print it as "Struct (*)(...)", for struct return functions.
398 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
399 const PAListPtr &PAL,
400 const PointerType *TheTy) {
401 const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
402 std::stringstream FunctionInnards;
403 FunctionInnards << " (*) (";
404 bool PrintedType = false;
406 FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
407 const Type *RetTy = cast<PointerType>(I->get())->getElementType();
409 for (++I, ++Idx; I != E; ++I, ++Idx) {
411 FunctionInnards << ", ";
412 const Type *ArgTy = *I;
413 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
414 assert(isa<PointerType>(ArgTy));
415 ArgTy = cast<PointerType>(ArgTy)->getElementType();
417 printType(FunctionInnards, ArgTy,
418 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt), "");
421 if (FTy->isVarArg()) {
423 FunctionInnards << ", ...";
424 } else if (!PrintedType) {
425 FunctionInnards << "void";
427 FunctionInnards << ')';
428 std::string tstr = FunctionInnards.str();
429 printType(Out, RetTy,
430 /*isSigned=*/PAL.paramHasAttr(0, ParamAttr::SExt), tstr);
434 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
435 const std::string &NameSoFar) {
436 assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
437 "Invalid type for printSimpleType");
438 switch (Ty->getTypeID()) {
439 case Type::VoidTyID: return Out << "void " << NameSoFar;
440 case Type::IntegerTyID: {
441 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
443 return Out << "bool " << NameSoFar;
444 else if (NumBits <= 8)
445 return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
446 else if (NumBits <= 16)
447 return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
448 else if (NumBits <= 32)
449 return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
450 else if (NumBits <= 64)
451 return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
453 assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
454 return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
457 case Type::FloatTyID: return Out << "float " << NameSoFar;
458 case Type::DoubleTyID: return Out << "double " << NameSoFar;
459 // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
460 // present matches host 'long double'.
461 case Type::X86_FP80TyID:
462 case Type::PPC_FP128TyID:
463 case Type::FP128TyID: return Out << "long double " << NameSoFar;
465 case Type::VectorTyID: {
466 const VectorType *VTy = cast<VectorType>(Ty);
467 return printSimpleType(Out, VTy->getElementType(), isSigned,
468 " __attribute__((vector_size(" +
469 utostr(TD->getABITypeSize(VTy)) + " ))) " + NameSoFar);
473 cerr << "Unknown primitive type: " << *Ty << "\n";
478 // Pass the Type* and the variable name and this prints out the variable
481 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
482 bool isSigned, const std::string &NameSoFar,
483 bool IgnoreName, const PAListPtr &PAL) {
484 if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
485 printSimpleType(Out, Ty, isSigned, NameSoFar);
489 // Check to see if the type is named.
490 if (!IgnoreName || isa<OpaqueType>(Ty)) {
491 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
492 if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
495 switch (Ty->getTypeID()) {
496 case Type::FunctionTyID: {
497 const FunctionType *FTy = cast<FunctionType>(Ty);
498 std::stringstream FunctionInnards;
499 FunctionInnards << " (" << NameSoFar << ") (";
501 for (FunctionType::param_iterator I = FTy->param_begin(),
502 E = FTy->param_end(); I != E; ++I) {
503 const Type *ArgTy = *I;
504 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
505 assert(isa<PointerType>(ArgTy));
506 ArgTy = cast<PointerType>(ArgTy)->getElementType();
508 if (I != FTy->param_begin())
509 FunctionInnards << ", ";
510 printType(FunctionInnards, ArgTy,
511 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt), "");
514 if (FTy->isVarArg()) {
515 if (FTy->getNumParams())
516 FunctionInnards << ", ...";
517 } else if (!FTy->getNumParams()) {
518 FunctionInnards << "void";
520 FunctionInnards << ')';
521 std::string tstr = FunctionInnards.str();
522 printType(Out, FTy->getReturnType(),
523 /*isSigned=*/PAL.paramHasAttr(0, ParamAttr::SExt), tstr);
526 case Type::StructTyID: {
527 const StructType *STy = cast<StructType>(Ty);
528 Out << NameSoFar + " {\n";
530 for (StructType::element_iterator I = STy->element_begin(),
531 E = STy->element_end(); I != E; ++I) {
533 printType(Out, *I, false, "field" + utostr(Idx++));
538 Out << " __attribute__ ((packed))";
542 case Type::PointerTyID: {
543 const PointerType *PTy = cast<PointerType>(Ty);
544 std::string ptrName = "*" + NameSoFar;
546 if (isa<ArrayType>(PTy->getElementType()) ||
547 isa<VectorType>(PTy->getElementType()))
548 ptrName = "(" + ptrName + ")";
551 // Must be a function ptr cast!
552 return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
553 return printType(Out, PTy->getElementType(), false, ptrName);
556 case Type::ArrayTyID: {
557 const ArrayType *ATy = cast<ArrayType>(Ty);
558 unsigned NumElements = ATy->getNumElements();
559 if (NumElements == 0) NumElements = 1;
560 return printType(Out, ATy->getElementType(), false,
561 NameSoFar + "[" + utostr(NumElements) + "]");
564 case Type::OpaqueTyID: {
565 static int Count = 0;
566 std::string TyName = "struct opaque_" + itostr(Count++);
567 assert(TypeNames.find(Ty) == TypeNames.end());
568 TypeNames[Ty] = TyName;
569 return Out << TyName << ' ' << NameSoFar;
572 assert(0 && "Unhandled case in getTypeProps!");
579 void CWriter::printConstantArray(ConstantArray *CPA) {
581 // As a special case, print the array as a string if it is an array of
582 // ubytes or an array of sbytes with positive values.
584 const Type *ETy = CPA->getType()->getElementType();
585 bool isString = (ETy == Type::Int8Ty || ETy == Type::Int8Ty);
587 // Make sure the last character is a null char, as automatically added by C
588 if (isString && (CPA->getNumOperands() == 0 ||
589 !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
594 // Keep track of whether the last number was a hexadecimal escape
595 bool LastWasHex = false;
597 // Do not include the last character, which we know is null
598 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
599 unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
601 // Print it out literally if it is a printable character. The only thing
602 // to be careful about is when the last letter output was a hex escape
603 // code, in which case we have to be careful not to print out hex digits
604 // explicitly (the C compiler thinks it is a continuation of the previous
605 // character, sheesh...)
607 if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
609 if (C == '"' || C == '\\')
616 case '\n': Out << "\\n"; break;
617 case '\t': Out << "\\t"; break;
618 case '\r': Out << "\\r"; break;
619 case '\v': Out << "\\v"; break;
620 case '\a': Out << "\\a"; break;
621 case '\"': Out << "\\\""; break;
622 case '\'': Out << "\\\'"; break;
625 Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
626 Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
635 if (CPA->getNumOperands()) {
637 printConstant(cast<Constant>(CPA->getOperand(0)));
638 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
640 printConstant(cast<Constant>(CPA->getOperand(i)));
647 void CWriter::printConstantVector(ConstantVector *CP) {
649 if (CP->getNumOperands()) {
651 printConstant(cast<Constant>(CP->getOperand(0)));
652 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
654 printConstant(cast<Constant>(CP->getOperand(i)));
660 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
661 // textually as a double (rather than as a reference to a stack-allocated
662 // variable). We decide this by converting CFP to a string and back into a
663 // double, and then checking whether the conversion results in a bit-equal
664 // double to the original value of CFP. This depends on us and the target C
665 // compiler agreeing on the conversion process (which is pretty likely since we
666 // only deal in IEEE FP).
668 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
669 // Do long doubles in hex for now.
670 if (CFP->getType()!=Type::FloatTy && CFP->getType()!=Type::DoubleTy)
672 APFloat APF = APFloat(CFP->getValueAPF()); // copy
673 if (CFP->getType()==Type::FloatTy)
674 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
675 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
677 sprintf(Buffer, "%a", APF.convertToDouble());
678 if (!strncmp(Buffer, "0x", 2) ||
679 !strncmp(Buffer, "-0x", 3) ||
680 !strncmp(Buffer, "+0x", 3))
681 return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
684 std::string StrVal = ftostr(APF);
686 while (StrVal[0] == ' ')
687 StrVal.erase(StrVal.begin());
689 // Check to make sure that the stringized number is not some string like "Inf"
690 // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
691 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
692 ((StrVal[0] == '-' || StrVal[0] == '+') &&
693 (StrVal[1] >= '0' && StrVal[1] <= '9')))
694 // Reparse stringized version!
695 return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
700 /// Print out the casting for a cast operation. This does the double casting
701 /// necessary for conversion to the destination type, if necessary.
702 /// @brief Print a cast
703 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
704 // Print the destination type cast
706 case Instruction::UIToFP:
707 case Instruction::SIToFP:
708 case Instruction::IntToPtr:
709 case Instruction::Trunc:
710 case Instruction::BitCast:
711 case Instruction::FPExt:
712 case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
714 printType(Out, DstTy);
717 case Instruction::ZExt:
718 case Instruction::PtrToInt:
719 case Instruction::FPToUI: // For these, make sure we get an unsigned dest
721 printSimpleType(Out, DstTy, false);
724 case Instruction::SExt:
725 case Instruction::FPToSI: // For these, make sure we get a signed dest
727 printSimpleType(Out, DstTy, true);
731 assert(0 && "Invalid cast opcode");
734 // Print the source type cast
736 case Instruction::UIToFP:
737 case Instruction::ZExt:
739 printSimpleType(Out, SrcTy, false);
742 case Instruction::SIToFP:
743 case Instruction::SExt:
745 printSimpleType(Out, SrcTy, true);
748 case Instruction::IntToPtr:
749 case Instruction::PtrToInt:
750 // Avoid "cast to pointer from integer of different size" warnings
751 Out << "(unsigned long)";
753 case Instruction::Trunc:
754 case Instruction::BitCast:
755 case Instruction::FPExt:
756 case Instruction::FPTrunc:
757 case Instruction::FPToSI:
758 case Instruction::FPToUI:
759 break; // These don't need a source cast.
761 assert(0 && "Invalid cast opcode");
766 // printConstant - The LLVM Constant to C Constant converter.
767 void CWriter::printConstant(Constant *CPV) {
768 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
769 switch (CE->getOpcode()) {
770 case Instruction::Trunc:
771 case Instruction::ZExt:
772 case Instruction::SExt:
773 case Instruction::FPTrunc:
774 case Instruction::FPExt:
775 case Instruction::UIToFP:
776 case Instruction::SIToFP:
777 case Instruction::FPToUI:
778 case Instruction::FPToSI:
779 case Instruction::PtrToInt:
780 case Instruction::IntToPtr:
781 case Instruction::BitCast:
783 printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
784 if (CE->getOpcode() == Instruction::SExt &&
785 CE->getOperand(0)->getType() == Type::Int1Ty) {
786 // Make sure we really sext from bool here by subtracting from 0
789 printConstant(CE->getOperand(0));
790 if (CE->getType() == Type::Int1Ty &&
791 (CE->getOpcode() == Instruction::Trunc ||
792 CE->getOpcode() == Instruction::FPToUI ||
793 CE->getOpcode() == Instruction::FPToSI ||
794 CE->getOpcode() == Instruction::PtrToInt)) {
795 // Make sure we really truncate to bool here by anding with 1
801 case Instruction::GetElementPtr:
803 printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
807 case Instruction::Select:
809 printConstant(CE->getOperand(0));
811 printConstant(CE->getOperand(1));
813 printConstant(CE->getOperand(2));
816 case Instruction::Add:
817 case Instruction::Sub:
818 case Instruction::Mul:
819 case Instruction::SDiv:
820 case Instruction::UDiv:
821 case Instruction::FDiv:
822 case Instruction::URem:
823 case Instruction::SRem:
824 case Instruction::FRem:
825 case Instruction::And:
826 case Instruction::Or:
827 case Instruction::Xor:
828 case Instruction::ICmp:
829 case Instruction::Shl:
830 case Instruction::LShr:
831 case Instruction::AShr:
834 bool NeedsClosingParens = printConstExprCast(CE);
835 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
836 switch (CE->getOpcode()) {
837 case Instruction::Add: Out << " + "; break;
838 case Instruction::Sub: Out << " - "; break;
839 case Instruction::Mul: Out << " * "; break;
840 case Instruction::URem:
841 case Instruction::SRem:
842 case Instruction::FRem: Out << " % "; break;
843 case Instruction::UDiv:
844 case Instruction::SDiv:
845 case Instruction::FDiv: Out << " / "; break;
846 case Instruction::And: Out << " & "; break;
847 case Instruction::Or: Out << " | "; break;
848 case Instruction::Xor: Out << " ^ "; break;
849 case Instruction::Shl: Out << " << "; break;
850 case Instruction::LShr:
851 case Instruction::AShr: Out << " >> "; break;
852 case Instruction::ICmp:
853 switch (CE->getPredicate()) {
854 case ICmpInst::ICMP_EQ: Out << " == "; break;
855 case ICmpInst::ICMP_NE: Out << " != "; break;
856 case ICmpInst::ICMP_SLT:
857 case ICmpInst::ICMP_ULT: Out << " < "; break;
858 case ICmpInst::ICMP_SLE:
859 case ICmpInst::ICMP_ULE: Out << " <= "; break;
860 case ICmpInst::ICMP_SGT:
861 case ICmpInst::ICMP_UGT: Out << " > "; break;
862 case ICmpInst::ICMP_SGE:
863 case ICmpInst::ICMP_UGE: Out << " >= "; break;
864 default: assert(0 && "Illegal ICmp predicate");
867 default: assert(0 && "Illegal opcode here!");
869 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
870 if (NeedsClosingParens)
875 case Instruction::FCmp: {
877 bool NeedsClosingParens = printConstExprCast(CE);
878 if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
880 else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
884 switch (CE->getPredicate()) {
885 default: assert(0 && "Illegal FCmp predicate");
886 case FCmpInst::FCMP_ORD: op = "ord"; break;
887 case FCmpInst::FCMP_UNO: op = "uno"; break;
888 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
889 case FCmpInst::FCMP_UNE: op = "une"; break;
890 case FCmpInst::FCMP_ULT: op = "ult"; break;
891 case FCmpInst::FCMP_ULE: op = "ule"; break;
892 case FCmpInst::FCMP_UGT: op = "ugt"; break;
893 case FCmpInst::FCMP_UGE: op = "uge"; break;
894 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
895 case FCmpInst::FCMP_ONE: op = "one"; break;
896 case FCmpInst::FCMP_OLT: op = "olt"; break;
897 case FCmpInst::FCMP_OLE: op = "ole"; break;
898 case FCmpInst::FCMP_OGT: op = "ogt"; break;
899 case FCmpInst::FCMP_OGE: op = "oge"; break;
901 Out << "llvm_fcmp_" << op << "(";
902 printConstantWithCast(CE->getOperand(0), CE->getOpcode());
904 printConstantWithCast(CE->getOperand(1), CE->getOpcode());
907 if (NeedsClosingParens)
913 cerr << "CWriter Error: Unhandled constant expression: "
917 } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
919 printType(Out, CPV->getType()); // sign doesn't matter
921 if (!isa<VectorType>(CPV->getType())) {
929 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
930 const Type* Ty = CI->getType();
931 if (Ty == Type::Int1Ty)
932 Out << (CI->getZExtValue() ? '1' : '0');
933 else if (Ty == Type::Int32Ty)
934 Out << CI->getZExtValue() << 'u';
935 else if (Ty->getPrimitiveSizeInBits() > 32)
936 Out << CI->getZExtValue() << "ull";
939 printSimpleType(Out, Ty, false) << ')';
940 if (CI->isMinValue(true))
941 Out << CI->getZExtValue() << 'u';
943 Out << CI->getSExtValue();
949 switch (CPV->getType()->getTypeID()) {
950 case Type::FloatTyID:
951 case Type::DoubleTyID:
952 case Type::X86_FP80TyID:
953 case Type::PPC_FP128TyID:
954 case Type::FP128TyID: {
955 ConstantFP *FPC = cast<ConstantFP>(CPV);
956 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
957 if (I != FPConstantMap.end()) {
958 // Because of FP precision problems we must load from a stack allocated
959 // value that holds the value in hex.
960 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" :
961 FPC->getType() == Type::DoubleTy ? "double" :
963 << "*)&FPConstant" << I->second << ')';
965 assert(FPC->getType() == Type::FloatTy ||
966 FPC->getType() == Type::DoubleTy);
967 double V = FPC->getType() == Type::FloatTy ?
968 FPC->getValueAPF().convertToFloat() :
969 FPC->getValueAPF().convertToDouble();
973 // FIXME the actual NaN bits should be emitted.
974 // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
976 const unsigned long QuietNaN = 0x7ff8UL;
977 //const unsigned long SignalNaN = 0x7ff4UL;
979 // We need to grab the first part of the FP #
982 uint64_t ll = DoubleToBits(V);
983 sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
985 std::string Num(&Buffer[0], &Buffer[6]);
986 unsigned long Val = strtoul(Num.c_str(), 0, 16);
988 if (FPC->getType() == Type::FloatTy)
989 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
990 << Buffer << "\") /*nan*/ ";
992 Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
993 << Buffer << "\") /*nan*/ ";
994 } else if (IsInf(V)) {
996 if (V < 0) Out << '-';
997 Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
1001 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
1002 // Print out the constant as a floating point number.
1004 sprintf(Buffer, "%a", V);
1007 Num = ftostr(FPC->getValueAPF());
1015 case Type::ArrayTyID:
1016 if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
1017 printConstantArray(CA);
1019 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1020 const ArrayType *AT = cast<ArrayType>(CPV->getType());
1022 if (AT->getNumElements()) {
1024 Constant *CZ = Constant::getNullValue(AT->getElementType());
1026 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
1035 case Type::VectorTyID:
1036 // Use C99 compound expression literal initializer syntax.
1038 printType(Out, CPV->getType());
1040 if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
1041 printConstantVector(CV);
1043 assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
1044 const VectorType *VT = cast<VectorType>(CPV->getType());
1046 Constant *CZ = Constant::getNullValue(VT->getElementType());
1048 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
1056 case Type::StructTyID:
1057 if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
1058 const StructType *ST = cast<StructType>(CPV->getType());
1060 if (ST->getNumElements()) {
1062 printConstant(Constant::getNullValue(ST->getElementType(0)));
1063 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
1065 printConstant(Constant::getNullValue(ST->getElementType(i)));
1071 if (CPV->getNumOperands()) {
1073 printConstant(cast<Constant>(CPV->getOperand(0)));
1074 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
1076 printConstant(cast<Constant>(CPV->getOperand(i)));
1083 case Type::PointerTyID:
1084 if (isa<ConstantPointerNull>(CPV)) {
1086 printType(Out, CPV->getType()); // sign doesn't matter
1087 Out << ")/*NULL*/0)";
1089 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
1095 cerr << "Unknown constant type: " << *CPV << "\n";
1100 // Some constant expressions need to be casted back to the original types
1101 // because their operands were casted to the expected type. This function takes
1102 // care of detecting that case and printing the cast for the ConstantExpr.
1103 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
1104 bool NeedsExplicitCast = false;
1105 const Type *Ty = CE->getOperand(0)->getType();
1106 bool TypeIsSigned = false;
1107 switch (CE->getOpcode()) {
1108 case Instruction::LShr:
1109 case Instruction::URem:
1110 case Instruction::UDiv: NeedsExplicitCast = true; break;
1111 case Instruction::AShr:
1112 case Instruction::SRem:
1113 case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
1114 case Instruction::SExt:
1116 NeedsExplicitCast = true;
1117 TypeIsSigned = true;
1119 case Instruction::ZExt:
1120 case Instruction::Trunc:
1121 case Instruction::FPTrunc:
1122 case Instruction::FPExt:
1123 case Instruction::UIToFP:
1124 case Instruction::SIToFP:
1125 case Instruction::FPToUI:
1126 case Instruction::FPToSI:
1127 case Instruction::PtrToInt:
1128 case Instruction::IntToPtr:
1129 case Instruction::BitCast:
1131 NeedsExplicitCast = true;
1135 if (NeedsExplicitCast) {
1137 if (Ty->isInteger() && Ty != Type::Int1Ty)
1138 printSimpleType(Out, Ty, TypeIsSigned);
1140 printType(Out, Ty); // not integer, sign doesn't matter
1143 return NeedsExplicitCast;
1146 // Print a constant assuming that it is the operand for a given Opcode. The
1147 // opcodes that care about sign need to cast their operands to the expected
1148 // type before the operation proceeds. This function does the casting.
1149 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
1151 // Extract the operand's type, we'll need it.
1152 const Type* OpTy = CPV->getType();
1154 // Indicate whether to do the cast or not.
1155 bool shouldCast = false;
1156 bool typeIsSigned = false;
1158 // Based on the Opcode for which this Constant is being written, determine
1159 // the new type to which the operand should be casted by setting the value
1160 // of OpTy. If we change OpTy, also set shouldCast to true so it gets
1164 // for most instructions, it doesn't matter
1166 case Instruction::LShr:
1167 case Instruction::UDiv:
1168 case Instruction::URem:
1171 case Instruction::AShr:
1172 case Instruction::SDiv:
1173 case Instruction::SRem:
1175 typeIsSigned = true;
1179 // Write out the casted constant if we should, otherwise just write the
1183 printSimpleType(Out, OpTy, typeIsSigned);
1191 std::string CWriter::GetValueName(const Value *Operand) {
1194 if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
1195 std::string VarName;
1197 Name = Operand->getName();
1198 VarName.reserve(Name.capacity());
1200 for (std::string::iterator I = Name.begin(), E = Name.end();
1204 if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
1205 (ch >= '0' && ch <= '9') || ch == '_')) {
1207 sprintf(buffer, "_%x_", ch);
1213 Name = "llvm_cbe_" + VarName;
1215 Name = Mang->getValueName(Operand);
1221 /// writeInstComputationInline - Emit the computation for the specified
1222 /// instruction inline, with no destination provided.
1223 void CWriter::writeInstComputationInline(Instruction &I) {
1224 // If this is a non-trivial bool computation, make sure to truncate down to
1225 // a 1 bit value. This is important because we want "add i1 x, y" to return
1226 // "0" when x and y are true, not "2" for example.
1227 bool NeedBoolTrunc = false;
1228 if (I.getType() == Type::Int1Ty && !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
1229 NeedBoolTrunc = true;
1241 void CWriter::writeOperandInternal(Value *Operand) {
1242 if (Instruction *I = dyn_cast<Instruction>(Operand))
1243 // Should we inline this instruction to build a tree?
1244 if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1246 writeInstComputationInline(*I);
1251 Constant* CPV = dyn_cast<Constant>(Operand);
1253 if (CPV && !isa<GlobalValue>(CPV))
1256 Out << GetValueName(Operand);
1259 void CWriter::writeOperandRaw(Value *Operand) {
1260 Constant* CPV = dyn_cast<Constant>(Operand);
1261 if (CPV && !isa<GlobalValue>(CPV)) {
1264 Out << GetValueName(Operand);
1268 void CWriter::writeOperand(Value *Operand) {
1269 bool isAddressImplicit = isAddressExposed(Operand);
1270 if (isAddressImplicit)
1271 Out << "(&"; // Global variables are referenced as their addresses by llvm
1273 writeOperandInternal(Operand);
1275 if (isAddressImplicit)
1279 // Some instructions need to have their result value casted back to the
1280 // original types because their operands were casted to the expected type.
1281 // This function takes care of detecting that case and printing the cast
1282 // for the Instruction.
1283 bool CWriter::writeInstructionCast(const Instruction &I) {
1284 const Type *Ty = I.getOperand(0)->getType();
1285 switch (I.getOpcode()) {
1286 case Instruction::LShr:
1287 case Instruction::URem:
1288 case Instruction::UDiv:
1290 printSimpleType(Out, Ty, false);
1293 case Instruction::AShr:
1294 case Instruction::SRem:
1295 case Instruction::SDiv:
1297 printSimpleType(Out, Ty, true);
1305 // Write the operand with a cast to another type based on the Opcode being used.
1306 // This will be used in cases where an instruction has specific type
1307 // requirements (usually signedness) for its operands.
1308 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1310 // Extract the operand's type, we'll need it.
1311 const Type* OpTy = Operand->getType();
1313 // Indicate whether to do the cast or not.
1314 bool shouldCast = false;
1316 // Indicate whether the cast should be to a signed type or not.
1317 bool castIsSigned = false;
1319 // Based on the Opcode for which this Operand is being written, determine
1320 // the new type to which the operand should be casted by setting the value
1321 // of OpTy. If we change OpTy, also set shouldCast to true.
1324 // for most instructions, it doesn't matter
1326 case Instruction::LShr:
1327 case Instruction::UDiv:
1328 case Instruction::URem: // Cast to unsigned first
1330 castIsSigned = false;
1332 case Instruction::GetElementPtr:
1333 case Instruction::AShr:
1334 case Instruction::SDiv:
1335 case Instruction::SRem: // Cast to signed first
1337 castIsSigned = true;
1341 // Write out the casted operand if we should, otherwise just write the
1345 printSimpleType(Out, OpTy, castIsSigned);
1347 writeOperand(Operand);
1350 writeOperand(Operand);
1353 // Write the operand with a cast to another type based on the icmp predicate
1355 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
1356 // This has to do a cast to ensure the operand has the right signedness.
1357 // Also, if the operand is a pointer, we make sure to cast to an integer when
1358 // doing the comparison both for signedness and so that the C compiler doesn't
1359 // optimize things like "p < NULL" to false (p may contain an integer value
1361 bool shouldCast = Cmp.isRelational();
1363 // Write out the casted operand if we should, otherwise just write the
1366 writeOperand(Operand);
1370 // Should this be a signed comparison? If so, convert to signed.
1371 bool castIsSigned = Cmp.isSignedPredicate();
1373 // If the operand was a pointer, convert to a large integer type.
1374 const Type* OpTy = Operand->getType();
1375 if (isa<PointerType>(OpTy))
1376 OpTy = TD->getIntPtrType();
1379 printSimpleType(Out, OpTy, castIsSigned);
1381 writeOperand(Operand);
1385 // generateCompilerSpecificCode - This is where we add conditional compilation
1386 // directives to cater to specific compilers as need be.
1388 static void generateCompilerSpecificCode(std::ostream& Out,
1389 const TargetData *TD) {
1390 // Alloca is hard to get, and we don't want to include stdlib.h here.
1391 Out << "/* get a declaration for alloca */\n"
1392 << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1393 << "#define alloca(x) __builtin_alloca((x))\n"
1394 << "#define _alloca(x) __builtin_alloca((x))\n"
1395 << "#elif defined(__APPLE__)\n"
1396 << "extern void *__builtin_alloca(unsigned long);\n"
1397 << "#define alloca(x) __builtin_alloca(x)\n"
1398 << "#define longjmp _longjmp\n"
1399 << "#define setjmp _setjmp\n"
1400 << "#elif defined(__sun__)\n"
1401 << "#if defined(__sparcv9)\n"
1402 << "extern void *__builtin_alloca(unsigned long);\n"
1404 << "extern void *__builtin_alloca(unsigned int);\n"
1406 << "#define alloca(x) __builtin_alloca(x)\n"
1407 << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)\n"
1408 << "#define alloca(x) __builtin_alloca(x)\n"
1409 << "#elif defined(_MSC_VER)\n"
1410 << "#define inline _inline\n"
1411 << "#define alloca(x) _alloca(x)\n"
1413 << "#include <alloca.h>\n"
1416 // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1417 // If we aren't being compiled with GCC, just drop these attributes.
1418 Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
1419 << "#define __attribute__(X)\n"
1422 // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1423 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1424 << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1425 << "#elif defined(__GNUC__)\n"
1426 << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1428 << "#define __EXTERNAL_WEAK__\n"
1431 // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1432 Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1433 << "#define __ATTRIBUTE_WEAK__\n"
1434 << "#elif defined(__GNUC__)\n"
1435 << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1437 << "#define __ATTRIBUTE_WEAK__\n"
1440 // Add hidden visibility support. FIXME: APPLE_CC?
1441 Out << "#if defined(__GNUC__)\n"
1442 << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
1445 // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1446 // From the GCC documentation:
1448 // double __builtin_nan (const char *str)
1450 // This is an implementation of the ISO C99 function nan.
1452 // Since ISO C99 defines this function in terms of strtod, which we do
1453 // not implement, a description of the parsing is in order. The string is
1454 // parsed as by strtol; that is, the base is recognized by leading 0 or
1455 // 0x prefixes. The number parsed is placed in the significand such that
1456 // the least significant bit of the number is at the least significant
1457 // bit of the significand. The number is truncated to fit the significand
1458 // field provided. The significand is forced to be a quiet NaN.
1460 // This function, if given a string literal, is evaluated early enough
1461 // that it is considered a compile-time constant.
1463 // float __builtin_nanf (const char *str)
1465 // Similar to __builtin_nan, except the return type is float.
1467 // double __builtin_inf (void)
1469 // Similar to __builtin_huge_val, except a warning is generated if the
1470 // target floating-point format does not support infinities. This
1471 // function is suitable for implementing the ISO C99 macro INFINITY.
1473 // float __builtin_inff (void)
1475 // Similar to __builtin_inf, except the return type is float.
1476 Out << "#ifdef __GNUC__\n"
1477 << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
1478 << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
1479 << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
1480 << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1481 << "#define LLVM_INF __builtin_inf() /* Double */\n"
1482 << "#define LLVM_INFF __builtin_inff() /* Float */\n"
1483 << "#define LLVM_PREFETCH(addr,rw,locality) "
1484 "__builtin_prefetch(addr,rw,locality)\n"
1485 << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1486 << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1487 << "#define LLVM_ASM __asm__\n"
1489 << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
1490 << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
1491 << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
1492 << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
1493 << "#define LLVM_INF ((double)0.0) /* Double */\n"
1494 << "#define LLVM_INFF 0.0F /* Float */\n"
1495 << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
1496 << "#define __ATTRIBUTE_CTOR__\n"
1497 << "#define __ATTRIBUTE_DTOR__\n"
1498 << "#define LLVM_ASM(X)\n"
1501 Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
1502 << "#define __builtin_stack_save() 0 /* not implemented */\n"
1503 << "#define __builtin_stack_restore(X) /* noop */\n"
1506 // Output typedefs for 128-bit integers. If these are needed with a
1507 // 32-bit target or with a C compiler that doesn't support mode(TI),
1508 // more drastic measures will be needed.
1509 if (TD->getPointerSize() >= 8) {
1510 Out << "#ifdef __GNUC__ /* 128-bit integer types */\n"
1511 << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
1512 << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
1516 // Output target-specific code that should be inserted into main.
1517 Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1520 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1521 /// the StaticTors set.
1522 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1523 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1524 if (!InitList) return;
1526 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1527 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1528 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1530 if (CS->getOperand(1)->isNullValue())
1531 return; // Found a null terminator, exit printing.
1532 Constant *FP = CS->getOperand(1);
1533 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1535 FP = CE->getOperand(0);
1536 if (Function *F = dyn_cast<Function>(FP))
1537 StaticTors.insert(F);
1541 enum SpecialGlobalClass {
1543 GlobalCtors, GlobalDtors,
1547 /// getGlobalVariableClass - If this is a global that is specially recognized
1548 /// by LLVM, return a code that indicates how we should handle it.
1549 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1550 // If this is a global ctors/dtors list, handle it now.
1551 if (GV->hasAppendingLinkage() && GV->use_empty()) {
1552 if (GV->getName() == "llvm.global_ctors")
1554 else if (GV->getName() == "llvm.global_dtors")
1558 // Otherwise, it it is other metadata, don't print it. This catches things
1559 // like debug information.
1560 if (GV->getSection() == "llvm.metadata")
1567 bool CWriter::doInitialization(Module &M) {
1571 TD = new TargetData(&M);
1572 IL = new IntrinsicLowering(*TD);
1573 IL->AddPrototypes(M);
1575 // Ensure that all structure types have names...
1576 Mang = new Mangler(M);
1577 Mang->markCharUnacceptable('.');
1579 // Keep track of which functions are static ctors/dtors so they can have
1580 // an attribute added to their prototypes.
1581 std::set<Function*> StaticCtors, StaticDtors;
1582 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1584 switch (getGlobalVariableClass(I)) {
1587 FindStaticTors(I, StaticCtors);
1590 FindStaticTors(I, StaticDtors);
1595 // get declaration for alloca
1596 Out << "/* Provide Declarations */\n";
1597 Out << "#include <stdarg.h>\n"; // Varargs support
1598 Out << "#include <setjmp.h>\n"; // Unwind support
1599 generateCompilerSpecificCode(Out, TD);
1601 // Provide a definition for `bool' if not compiling with a C++ compiler.
1603 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1605 << "\n\n/* Support for floating point constants */\n"
1606 << "typedef unsigned long long ConstantDoubleTy;\n"
1607 << "typedef unsigned int ConstantFloatTy;\n"
1608 << "typedef struct { unsigned long long f1; unsigned short f2; "
1609 "unsigned short pad[3]; } ConstantFP80Ty;\n"
1610 // This is used for both kinds of 128-bit long double; meaning differs.
1611 << "typedef struct { unsigned long long f1; unsigned long long f2; }"
1612 " ConstantFP128Ty;\n"
1613 << "\n\n/* Global Declarations */\n";
1615 // First output all the declarations for the program, because C requires
1616 // Functions & globals to be declared before they are used.
1619 // Loop over the symbol table, emitting all named constants...
1620 printModuleTypes(M.getTypeSymbolTable());
1622 // Global variable declarations...
1623 if (!M.global_empty()) {
1624 Out << "\n/* External Global Variable Declarations */\n";
1625 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1628 if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
1629 I->hasCommonLinkage())
1631 else if (I->hasDLLImportLinkage())
1632 Out << "__declspec(dllimport) ";
1634 continue; // Internal Global
1636 // Thread Local Storage
1637 if (I->isThreadLocal())
1640 printType(Out, I->getType()->getElementType(), false, GetValueName(I));
1642 if (I->hasExternalWeakLinkage())
1643 Out << " __EXTERNAL_WEAK__";
1648 // Function declarations
1649 Out << "\n/* Function Declarations */\n";
1650 Out << "double fmod(double, double);\n"; // Support for FP rem
1651 Out << "float fmodf(float, float);\n";
1652 Out << "long double fmodl(long double, long double);\n";
1654 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1655 // Don't print declarations for intrinsic functions.
1656 if (!I->isIntrinsic() && I->getName() != "setjmp" &&
1657 I->getName() != "longjmp" && I->getName() != "_setjmp") {
1658 if (I->hasExternalWeakLinkage())
1660 printFunctionSignature(I, true);
1661 if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1662 Out << " __ATTRIBUTE_WEAK__";
1663 if (I->hasExternalWeakLinkage())
1664 Out << " __EXTERNAL_WEAK__";
1665 if (StaticCtors.count(I))
1666 Out << " __ATTRIBUTE_CTOR__";
1667 if (StaticDtors.count(I))
1668 Out << " __ATTRIBUTE_DTOR__";
1669 if (I->hasHiddenVisibility())
1670 Out << " __HIDDEN__";
1672 if (I->hasName() && I->getName()[0] == 1)
1673 Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1679 // Output the global variable declarations
1680 if (!M.global_empty()) {
1681 Out << "\n\n/* Global Variable Declarations */\n";
1682 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1684 if (!I->isDeclaration()) {
1685 // Ignore special globals, such as debug info.
1686 if (getGlobalVariableClass(I))
1689 if (I->hasInternalLinkage())
1694 // Thread Local Storage
1695 if (I->isThreadLocal())
1698 printType(Out, I->getType()->getElementType(), false,
1701 if (I->hasLinkOnceLinkage())
1702 Out << " __attribute__((common))";
1703 else if (I->hasCommonLinkage()) // FIXME is this right?
1704 Out << " __ATTRIBUTE_WEAK__";
1705 else if (I->hasWeakLinkage())
1706 Out << " __ATTRIBUTE_WEAK__";
1707 else if (I->hasExternalWeakLinkage())
1708 Out << " __EXTERNAL_WEAK__";
1709 if (I->hasHiddenVisibility())
1710 Out << " __HIDDEN__";
1715 // Output the global variable definitions and contents...
1716 if (!M.global_empty()) {
1717 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1718 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1720 if (!I->isDeclaration()) {
1721 // Ignore special globals, such as debug info.
1722 if (getGlobalVariableClass(I))
1725 if (I->hasInternalLinkage())
1727 else if (I->hasDLLImportLinkage())
1728 Out << "__declspec(dllimport) ";
1729 else if (I->hasDLLExportLinkage())
1730 Out << "__declspec(dllexport) ";
1732 // Thread Local Storage
1733 if (I->isThreadLocal())
1736 printType(Out, I->getType()->getElementType(), false,
1738 if (I->hasLinkOnceLinkage())
1739 Out << " __attribute__((common))";
1740 else if (I->hasWeakLinkage())
1741 Out << " __ATTRIBUTE_WEAK__";
1742 else if (I->hasCommonLinkage())
1743 Out << " __ATTRIBUTE_WEAK__";
1745 if (I->hasHiddenVisibility())
1746 Out << " __HIDDEN__";
1748 // If the initializer is not null, emit the initializer. If it is null,
1749 // we try to avoid emitting large amounts of zeros. The problem with
1750 // this, however, occurs when the variable has weak linkage. In this
1751 // case, the assembler will complain about the variable being both weak
1752 // and common, so we disable this optimization.
1753 // FIXME common linkage should avoid this problem.
1754 if (!I->getInitializer()->isNullValue()) {
1756 writeOperand(I->getInitializer());
1757 } else if (I->hasWeakLinkage()) {
1758 // We have to specify an initializer, but it doesn't have to be
1759 // complete. If the value is an aggregate, print out { 0 }, and let
1760 // the compiler figure out the rest of the zeros.
1762 if (isa<StructType>(I->getInitializer()->getType()) ||
1763 isa<ArrayType>(I->getInitializer()->getType()) ||
1764 isa<VectorType>(I->getInitializer()->getType())) {
1767 // Just print it out normally.
1768 writeOperand(I->getInitializer());
1776 Out << "\n\n/* Function Bodies */\n";
1778 // Emit some helper functions for dealing with FCMP instruction's
1780 Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
1781 Out << "return X == X && Y == Y; }\n";
1782 Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
1783 Out << "return X != X || Y != Y; }\n";
1784 Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
1785 Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
1786 Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
1787 Out << "return X != Y; }\n";
1788 Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
1789 Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
1790 Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
1791 Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
1792 Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
1793 Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
1794 Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
1795 Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
1796 Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
1797 Out << "return X == Y ; }\n";
1798 Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
1799 Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
1800 Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
1801 Out << "return X < Y ; }\n";
1802 Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
1803 Out << "return X > Y ; }\n";
1804 Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
1805 Out << "return X <= Y ; }\n";
1806 Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
1807 Out << "return X >= Y ; }\n";
1812 /// Output all floating point constants that cannot be printed accurately...
1813 void CWriter::printFloatingPointConstants(Function &F) {
1814 // Scan the module for floating point constants. If any FP constant is used
1815 // in the function, we want to redirect it here so that we do not depend on
1816 // the precision of the printed form, unless the printed form preserves
1819 static unsigned FPCounter = 0;
1820 for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1822 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1823 if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1824 !FPConstantMap.count(FPC)) {
1825 FPConstantMap[FPC] = FPCounter; // Number the FP constants
1827 if (FPC->getType() == Type::DoubleTy) {
1828 double Val = FPC->getValueAPF().convertToDouble();
1829 uint64_t i = FPC->getValueAPF().convertToAPInt().getZExtValue();
1830 Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1831 << " = 0x" << std::hex << i << std::dec
1832 << "ULL; /* " << Val << " */\n";
1833 } else if (FPC->getType() == Type::FloatTy) {
1834 float Val = FPC->getValueAPF().convertToFloat();
1835 uint32_t i = (uint32_t)FPC->getValueAPF().convertToAPInt().
1837 Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1838 << " = 0x" << std::hex << i << std::dec
1839 << "U; /* " << Val << " */\n";
1840 } else if (FPC->getType() == Type::X86_FP80Ty) {
1841 // api needed to prevent premature destruction
1842 APInt api = FPC->getValueAPF().convertToAPInt();
1843 const uint64_t *p = api.getRawData();
1844 Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
1845 << " = { 0x" << std::hex
1846 << ((uint16_t)p[1] | (p[0] & 0xffffffffffffLL)<<16)
1847 << "ULL, 0x" << (uint16_t)(p[0] >> 48) << ",{0,0,0}"
1848 << "}; /* Long double constant */\n" << std::dec;
1849 } else if (FPC->getType() == Type::PPC_FP128Ty) {
1850 APInt api = FPC->getValueAPF().convertToAPInt();
1851 const uint64_t *p = api.getRawData();
1852 Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
1853 << " = { 0x" << std::hex
1854 << p[0] << ", 0x" << p[1]
1855 << "}; /* Long double constant */\n" << std::dec;
1858 assert(0 && "Unknown float type!");
1865 /// printSymbolTable - Run through symbol table looking for type names. If a
1866 /// type name is found, emit its declaration...
1868 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
1869 Out << "/* Helper union for bitcasts */\n";
1870 Out << "typedef union {\n";
1871 Out << " unsigned int Int32;\n";
1872 Out << " unsigned long long Int64;\n";
1873 Out << " float Float;\n";
1874 Out << " double Double;\n";
1875 Out << "} llvmBitCastUnion;\n";
1877 // We are only interested in the type plane of the symbol table.
1878 TypeSymbolTable::const_iterator I = TST.begin();
1879 TypeSymbolTable::const_iterator End = TST.end();
1881 // If there are no type names, exit early.
1882 if (I == End) return;
1884 // Print out forward declarations for structure types before anything else!
1885 Out << "/* Structure forward decls */\n";
1886 for (; I != End; ++I) {
1887 std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1888 Out << Name << ";\n";
1889 TypeNames.insert(std::make_pair(I->second, Name));
1894 // Now we can print out typedefs. Above, we guaranteed that this can only be
1895 // for struct or opaque types.
1896 Out << "/* Typedefs */\n";
1897 for (I = TST.begin(); I != End; ++I) {
1898 std::string Name = "l_" + Mang->makeNameProper(I->first);
1900 printType(Out, I->second, false, Name);
1906 // Keep track of which structures have been printed so far...
1907 std::set<const StructType *> StructPrinted;
1909 // Loop over all structures then push them into the stack so they are
1910 // printed in the correct order.
1912 Out << "/* Structure contents */\n";
1913 for (I = TST.begin(); I != End; ++I)
1914 if (const StructType *STy = dyn_cast<StructType>(I->second))
1915 // Only print out used types!
1916 printContainedStructs(STy, StructPrinted);
1919 // Push the struct onto the stack and recursively push all structs
1920 // this one depends on.
1922 // TODO: Make this work properly with vector types
1924 void CWriter::printContainedStructs(const Type *Ty,
1925 std::set<const StructType*> &StructPrinted){
1926 // Don't walk through pointers.
1927 if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
1929 // Print all contained types first.
1930 for (Type::subtype_iterator I = Ty->subtype_begin(),
1931 E = Ty->subtype_end(); I != E; ++I)
1932 printContainedStructs(*I, StructPrinted);
1934 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1935 // Check to see if we have already printed this struct.
1936 if (StructPrinted.insert(STy).second) {
1937 // Print structure type out.
1938 std::string Name = TypeNames[STy];
1939 printType(Out, STy, false, Name, true);
1945 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1946 /// isStructReturn - Should this function actually return a struct by-value?
1947 bool isStructReturn = F->hasStructRetAttr();
1949 if (F->hasInternalLinkage()) Out << "static ";
1950 if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1951 if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
1952 switch (F->getCallingConv()) {
1953 case CallingConv::X86_StdCall:
1954 Out << "__stdcall ";
1956 case CallingConv::X86_FastCall:
1957 Out << "__fastcall ";
1961 // Loop over the arguments, printing them...
1962 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1963 const PAListPtr &PAL = F->getParamAttrs();
1965 std::stringstream FunctionInnards;
1967 // Print out the name...
1968 FunctionInnards << GetValueName(F) << '(';
1970 bool PrintedArg = false;
1971 if (!F->isDeclaration()) {
1972 if (!F->arg_empty()) {
1973 Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1976 // If this is a struct-return function, don't print the hidden
1977 // struct-return argument.
1978 if (isStructReturn) {
1979 assert(I != E && "Invalid struct return function!");
1984 std::string ArgName;
1985 for (; I != E; ++I) {
1986 if (PrintedArg) FunctionInnards << ", ";
1987 if (I->hasName() || !Prototype)
1988 ArgName = GetValueName(I);
1991 const Type *ArgTy = I->getType();
1992 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
1993 ArgTy = cast<PointerType>(ArgTy)->getElementType();
1994 ByValParams.insert(I);
1996 printType(FunctionInnards, ArgTy,
1997 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt),
2004 // Loop over the arguments, printing them.
2005 FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
2008 // If this is a struct-return function, don't print the hidden
2009 // struct-return argument.
2010 if (isStructReturn) {
2011 assert(I != E && "Invalid struct return function!");
2016 for (; I != E; ++I) {
2017 if (PrintedArg) FunctionInnards << ", ";
2018 const Type *ArgTy = *I;
2019 if (PAL.paramHasAttr(Idx, ParamAttr::ByVal)) {
2020 assert(isa<PointerType>(ArgTy));
2021 ArgTy = cast<PointerType>(ArgTy)->getElementType();
2023 printType(FunctionInnards, ArgTy,
2024 /*isSigned=*/PAL.paramHasAttr(Idx, ParamAttr::SExt));
2030 // Finish printing arguments... if this is a vararg function, print the ...,
2031 // unless there are no known types, in which case, we just emit ().
2033 if (FT->isVarArg() && PrintedArg) {
2034 if (PrintedArg) FunctionInnards << ", ";
2035 FunctionInnards << "..."; // Output varargs portion of signature!
2036 } else if (!FT->isVarArg() && !PrintedArg) {
2037 FunctionInnards << "void"; // ret() -> ret(void) in C.
2039 FunctionInnards << ')';
2041 // Get the return tpe for the function.
2043 if (!isStructReturn)
2044 RetTy = F->getReturnType();
2046 // If this is a struct-return function, print the struct-return type.
2047 RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
2050 // Print out the return type and the signature built above.
2051 printType(Out, RetTy,
2052 /*isSigned=*/PAL.paramHasAttr(0, ParamAttr::SExt),
2053 FunctionInnards.str());
2056 static inline bool isFPIntBitCast(const Instruction &I) {
2057 if (!isa<BitCastInst>(I))
2059 const Type *SrcTy = I.getOperand(0)->getType();
2060 const Type *DstTy = I.getType();
2061 return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
2062 (DstTy->isFloatingPoint() && SrcTy->isInteger());
2065 void CWriter::printFunction(Function &F) {
2066 /// isStructReturn - Should this function actually return a struct by-value?
2067 bool isStructReturn = F.hasStructRetAttr();
2069 printFunctionSignature(&F, false);
2072 // If this is a struct return function, handle the result with magic.
2073 if (isStructReturn) {
2074 const Type *StructTy =
2075 cast<PointerType>(F.arg_begin()->getType())->getElementType();
2077 printType(Out, StructTy, false, "StructReturn");
2078 Out << "; /* Struct return temporary */\n";
2081 printType(Out, F.arg_begin()->getType(), false,
2082 GetValueName(F.arg_begin()));
2083 Out << " = &StructReturn;\n";
2086 bool PrintedVar = false;
2088 // print local variable information for the function
2089 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
2090 if (const AllocaInst *AI = isDirectAlloca(&*I)) {
2092 printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
2093 Out << "; /* Address-exposed local */\n";
2095 } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
2097 printType(Out, I->getType(), false, GetValueName(&*I));
2100 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
2102 printType(Out, I->getType(), false,
2103 GetValueName(&*I)+"__PHI_TEMPORARY");
2108 // We need a temporary for the BitCast to use so it can pluck a value out
2109 // of a union to do the BitCast. This is separate from the need for a
2110 // variable to hold the result of the BitCast.
2111 if (isFPIntBitCast(*I)) {
2112 Out << " llvmBitCastUnion " << GetValueName(&*I)
2113 << "__BITCAST_TEMPORARY;\n";
2121 if (F.hasExternalLinkage() && F.getName() == "main")
2122 Out << " CODE_FOR_MAIN();\n";
2124 // print the basic blocks
2125 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2126 if (Loop *L = LI->getLoopFor(BB)) {
2127 if (L->getHeader() == BB && L->getParentLoop() == 0)
2130 printBasicBlock(BB);
2137 void CWriter::printLoop(Loop *L) {
2138 Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
2139 << "' to make GCC happy */\n";
2140 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
2141 BasicBlock *BB = L->getBlocks()[i];
2142 Loop *BBLoop = LI->getLoopFor(BB);
2144 printBasicBlock(BB);
2145 else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
2148 Out << " } while (1); /* end of syntactic loop '"
2149 << L->getHeader()->getName() << "' */\n";
2152 void CWriter::printBasicBlock(BasicBlock *BB) {
2154 // Don't print the label for the basic block if there are no uses, or if
2155 // the only terminator use is the predecessor basic block's terminator.
2156 // We have to scan the use list because PHI nodes use basic blocks too but
2157 // do not require a label to be generated.
2159 bool NeedsLabel = false;
2160 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2161 if (isGotoCodeNecessary(*PI, BB)) {
2166 if (NeedsLabel) Out << GetValueName(BB) << ":\n";
2168 // Output all of the instructions in the basic block...
2169 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
2171 if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
2172 if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
2176 writeInstComputationInline(*II);
2181 // Don't emit prefix or suffix for the terminator.
2182 visit(*BB->getTerminator());
2186 // Specific Instruction type classes... note that all of the casts are
2187 // necessary because we use the instruction classes as opaque types...
2189 void CWriter::visitReturnInst(ReturnInst &I) {
2190 // If this is a struct return function, return the temporary struct.
2191 bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
2193 if (isStructReturn) {
2194 Out << " return StructReturn;\n";
2198 // Don't output a void return if this is the last basic block in the function
2199 if (I.getNumOperands() == 0 &&
2200 &*--I.getParent()->getParent()->end() == I.getParent() &&
2201 !I.getParent()->size() == 1) {
2205 if (I.getNumOperands() > 1) {
2208 printType(Out, I.getParent()->getParent()->getReturnType());
2209 Out << " llvm_cbe_mrv_temp = {\n";
2210 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2212 writeOperand(I.getOperand(i));
2218 Out << " return llvm_cbe_mrv_temp;\n";
2224 if (I.getNumOperands()) {
2226 writeOperand(I.getOperand(0));
2231 void CWriter::visitSwitchInst(SwitchInst &SI) {
2234 writeOperand(SI.getOperand(0));
2235 Out << ") {\n default:\n";
2236 printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
2237 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
2239 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
2241 writeOperand(SI.getOperand(i));
2243 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
2244 printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
2245 printBranchToBlock(SI.getParent(), Succ, 2);
2246 if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
2252 void CWriter::visitUnreachableInst(UnreachableInst &I) {
2253 Out << " /*UNREACHABLE*/;\n";
2256 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
2257 /// FIXME: This should be reenabled, but loop reordering safe!!
2260 if (next(Function::iterator(From)) != Function::iterator(To))
2261 return true; // Not the direct successor, we need a goto.
2263 //isa<SwitchInst>(From->getTerminator())
2265 if (LI->getLoopFor(From) != LI->getLoopFor(To))
2270 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
2271 BasicBlock *Successor,
2273 for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
2274 PHINode *PN = cast<PHINode>(I);
2275 // Now we have to do the printing.
2276 Value *IV = PN->getIncomingValueForBlock(CurBlock);
2277 if (!isa<UndefValue>(IV)) {
2278 Out << std::string(Indent, ' ');
2279 Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
2281 Out << "; /* for PHI node */\n";
2286 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
2288 if (isGotoCodeNecessary(CurBB, Succ)) {
2289 Out << std::string(Indent, ' ') << " goto ";
2295 // Branch instruction printing - Avoid printing out a branch to a basic block
2296 // that immediately succeeds the current one.
2298 void CWriter::visitBranchInst(BranchInst &I) {
2300 if (I.isConditional()) {
2301 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
2303 writeOperand(I.getCondition());
2306 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
2307 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
2309 if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
2310 Out << " } else {\n";
2311 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2312 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2315 // First goto not necessary, assume second one is...
2317 writeOperand(I.getCondition());
2320 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
2321 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
2326 printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
2327 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
2332 // PHI nodes get copied into temporary values at the end of predecessor basic
2333 // blocks. We now need to copy these temporary values into the REAL value for
2335 void CWriter::visitPHINode(PHINode &I) {
2337 Out << "__PHI_TEMPORARY";
2341 void CWriter::visitBinaryOperator(Instruction &I) {
2342 // binary instructions, shift instructions, setCond instructions.
2343 assert(!isa<PointerType>(I.getType()));
2345 // We must cast the results of binary operations which might be promoted.
2346 bool needsCast = false;
2347 if ((I.getType() == Type::Int8Ty) || (I.getType() == Type::Int16Ty)
2348 || (I.getType() == Type::FloatTy)) {
2351 printType(Out, I.getType(), false);
2355 // If this is a negation operation, print it out as such. For FP, we don't
2356 // want to print "-0.0 - X".
2357 if (BinaryOperator::isNeg(&I)) {
2359 writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
2361 } else if (I.getOpcode() == Instruction::FRem) {
2362 // Output a call to fmod/fmodf instead of emitting a%b
2363 if (I.getType() == Type::FloatTy)
2365 else if (I.getType() == Type::DoubleTy)
2367 else // all 3 flavors of long double
2369 writeOperand(I.getOperand(0));
2371 writeOperand(I.getOperand(1));
2375 // Write out the cast of the instruction's value back to the proper type
2377 bool NeedsClosingParens = writeInstructionCast(I);
2379 // Certain instructions require the operand to be forced to a specific type
2380 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2381 // below for operand 1
2382 writeOperandWithCast(I.getOperand(0), I.getOpcode());
2384 switch (I.getOpcode()) {
2385 case Instruction::Add: Out << " + "; break;
2386 case Instruction::Sub: Out << " - "; break;
2387 case Instruction::Mul: Out << " * "; break;
2388 case Instruction::URem:
2389 case Instruction::SRem:
2390 case Instruction::FRem: Out << " % "; break;
2391 case Instruction::UDiv:
2392 case Instruction::SDiv:
2393 case Instruction::FDiv: Out << " / "; break;
2394 case Instruction::And: Out << " & "; break;
2395 case Instruction::Or: Out << " | "; break;
2396 case Instruction::Xor: Out << " ^ "; break;
2397 case Instruction::Shl : Out << " << "; break;
2398 case Instruction::LShr:
2399 case Instruction::AShr: Out << " >> "; break;
2400 default: cerr << "Invalid operator type!" << I; abort();
2403 writeOperandWithCast(I.getOperand(1), I.getOpcode());
2404 if (NeedsClosingParens)
2413 void CWriter::visitICmpInst(ICmpInst &I) {
2414 // We must cast the results of icmp which might be promoted.
2415 bool needsCast = false;
2417 // Write out the cast of the instruction's value back to the proper type
2419 bool NeedsClosingParens = writeInstructionCast(I);
2421 // Certain icmp predicate require the operand to be forced to a specific type
2422 // so we use writeOperandWithCast here instead of writeOperand. Similarly
2423 // below for operand 1
2424 writeOperandWithCast(I.getOperand(0), I);
2426 switch (I.getPredicate()) {
2427 case ICmpInst::ICMP_EQ: Out << " == "; break;
2428 case ICmpInst::ICMP_NE: Out << " != "; break;
2429 case ICmpInst::ICMP_ULE:
2430 case ICmpInst::ICMP_SLE: Out << " <= "; break;
2431 case ICmpInst::ICMP_UGE:
2432 case ICmpInst::ICMP_SGE: Out << " >= "; break;
2433 case ICmpInst::ICMP_ULT:
2434 case ICmpInst::ICMP_SLT: Out << " < "; break;
2435 case ICmpInst::ICMP_UGT:
2436 case ICmpInst::ICMP_SGT: Out << " > "; break;
2437 default: cerr << "Invalid icmp predicate!" << I; abort();
2440 writeOperandWithCast(I.getOperand(1), I);
2441 if (NeedsClosingParens)
2449 void CWriter::visitFCmpInst(FCmpInst &I) {
2450 if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
2454 if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
2460 switch (I.getPredicate()) {
2461 default: assert(0 && "Illegal FCmp predicate");
2462 case FCmpInst::FCMP_ORD: op = "ord"; break;
2463 case FCmpInst::FCMP_UNO: op = "uno"; break;
2464 case FCmpInst::FCMP_UEQ: op = "ueq"; break;
2465 case FCmpInst::FCMP_UNE: op = "une"; break;
2466 case FCmpInst::FCMP_ULT: op = "ult"; break;
2467 case FCmpInst::FCMP_ULE: op = "ule"; break;
2468 case FCmpInst::FCMP_UGT: op = "ugt"; break;
2469 case FCmpInst::FCMP_UGE: op = "uge"; break;
2470 case FCmpInst::FCMP_OEQ: op = "oeq"; break;
2471 case FCmpInst::FCMP_ONE: op = "one"; break;
2472 case FCmpInst::FCMP_OLT: op = "olt"; break;
2473 case FCmpInst::FCMP_OLE: op = "ole"; break;
2474 case FCmpInst::FCMP_OGT: op = "ogt"; break;
2475 case FCmpInst::FCMP_OGE: op = "oge"; break;
2478 Out << "llvm_fcmp_" << op << "(";
2479 // Write the first operand
2480 writeOperand(I.getOperand(0));
2482 // Write the second operand
2483 writeOperand(I.getOperand(1));
2487 static const char * getFloatBitCastField(const Type *Ty) {
2488 switch (Ty->getTypeID()) {
2489 default: assert(0 && "Invalid Type");
2490 case Type::FloatTyID: return "Float";
2491 case Type::DoubleTyID: return "Double";
2492 case Type::IntegerTyID: {
2493 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
2502 void CWriter::visitCastInst(CastInst &I) {
2503 const Type *DstTy = I.getType();
2504 const Type *SrcTy = I.getOperand(0)->getType();
2505 if (isFPIntBitCast(I)) {
2507 // These int<->float and long<->double casts need to be handled specially
2508 Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
2509 << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
2510 writeOperand(I.getOperand(0));
2511 Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
2512 << getFloatBitCastField(I.getType());
2518 printCast(I.getOpcode(), SrcTy, DstTy);
2520 // Make a sext from i1 work by subtracting the i1 from 0 (an int).
2521 if (SrcTy == Type::Int1Ty && I.getOpcode() == Instruction::SExt)
2524 writeOperand(I.getOperand(0));
2526 if (DstTy == Type::Int1Ty &&
2527 (I.getOpcode() == Instruction::Trunc ||
2528 I.getOpcode() == Instruction::FPToUI ||
2529 I.getOpcode() == Instruction::FPToSI ||
2530 I.getOpcode() == Instruction::PtrToInt)) {
2531 // Make sure we really get a trunc to bool by anding the operand with 1
2537 void CWriter::visitSelectInst(SelectInst &I) {
2539 writeOperand(I.getCondition());
2541 writeOperand(I.getTrueValue());
2543 writeOperand(I.getFalseValue());
2548 void CWriter::lowerIntrinsics(Function &F) {
2549 // This is used to keep track of intrinsics that get generated to a lowered
2550 // function. We must generate the prototypes before the function body which
2551 // will only be expanded on first use (by the loop below).
2552 std::vector<Function*> prototypesToGen;
2554 // Examine all the instructions in this function to find the intrinsics that
2555 // need to be lowered.
2556 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
2557 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2558 if (CallInst *CI = dyn_cast<CallInst>(I++))
2559 if (Function *F = CI->getCalledFunction())
2560 switch (F->getIntrinsicID()) {
2561 case Intrinsic::not_intrinsic:
2562 case Intrinsic::memory_barrier:
2563 case Intrinsic::vastart:
2564 case Intrinsic::vacopy:
2565 case Intrinsic::vaend:
2566 case Intrinsic::returnaddress:
2567 case Intrinsic::frameaddress:
2568 case Intrinsic::setjmp:
2569 case Intrinsic::longjmp:
2570 case Intrinsic::prefetch:
2571 case Intrinsic::dbg_stoppoint:
2572 case Intrinsic::powi:
2573 case Intrinsic::x86_sse_cmp_ss:
2574 case Intrinsic::x86_sse_cmp_ps:
2575 case Intrinsic::x86_sse2_cmp_sd:
2576 case Intrinsic::x86_sse2_cmp_pd:
2577 case Intrinsic::ppc_altivec_lvsl:
2578 // We directly implement these intrinsics
2581 // If this is an intrinsic that directly corresponds to a GCC
2582 // builtin, we handle it.
2583 const char *BuiltinName = "";
2584 #define GET_GCC_BUILTIN_NAME
2585 #include "llvm/Intrinsics.gen"
2586 #undef GET_GCC_BUILTIN_NAME
2587 // If we handle it, don't lower it.
2588 if (BuiltinName[0]) break;
2590 // All other intrinsic calls we must lower.
2591 Instruction *Before = 0;
2592 if (CI != &BB->front())
2593 Before = prior(BasicBlock::iterator(CI));
2595 IL->LowerIntrinsicCall(CI);
2596 if (Before) { // Move iterator to instruction after call
2601 // If the intrinsic got lowered to another call, and that call has
2602 // a definition then we need to make sure its prototype is emitted
2603 // before any calls to it.
2604 if (CallInst *Call = dyn_cast<CallInst>(I))
2605 if (Function *NewF = Call->getCalledFunction())
2606 if (!NewF->isDeclaration())
2607 prototypesToGen.push_back(NewF);
2612 // We may have collected some prototypes to emit in the loop above.
2613 // Emit them now, before the function that uses them is emitted. But,
2614 // be careful not to emit them twice.
2615 std::vector<Function*>::iterator I = prototypesToGen.begin();
2616 std::vector<Function*>::iterator E = prototypesToGen.end();
2617 for ( ; I != E; ++I) {
2618 if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
2620 printFunctionSignature(*I, true);
2626 void CWriter::visitCallInst(CallInst &I) {
2627 if (isa<InlineAsm>(I.getOperand(0)))
2628 return visitInlineAsm(I);
2630 bool WroteCallee = false;
2632 // Handle intrinsic function calls first...
2633 if (Function *F = I.getCalledFunction())
2634 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2635 if (visitBuiltinCall(I, ID, WroteCallee))
2638 Value *Callee = I.getCalledValue();
2640 const PointerType *PTy = cast<PointerType>(Callee->getType());
2641 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2643 // If this is a call to a struct-return function, assign to the first
2644 // parameter instead of passing it to the call.
2645 const PAListPtr &PAL = I.getParamAttrs();
2646 bool hasByVal = I.hasByValArgument();
2647 bool isStructRet = I.hasStructRetAttr();
2649 writeOperandDeref(I.getOperand(1));
2653 if (I.isTailCall()) Out << " /*tail*/ ";
2656 // If this is an indirect call to a struct return function, we need to cast
2657 // the pointer. Ditto for indirect calls with byval arguments.
2658 bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
2660 // GCC is a real PITA. It does not permit codegening casts of functions to
2661 // function pointers if they are in a call (it generates a trap instruction
2662 // instead!). We work around this by inserting a cast to void* in between
2663 // the function and the function pointer cast. Unfortunately, we can't just
2664 // form the constant expression here, because the folder will immediately
2667 // Note finally, that this is completely unsafe. ANSI C does not guarantee
2668 // that void* and function pointers have the same size. :( To deal with this
2669 // in the common case, we handle casts where the number of arguments passed
2672 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2674 if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2680 // Ok, just cast the pointer type.
2683 printStructReturnPointerFunctionType(Out, PAL,
2684 cast<PointerType>(I.getCalledValue()->getType()));
2686 printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
2688 printType(Out, I.getCalledValue()->getType());
2691 writeOperand(Callee);
2692 if (NeedsCast) Out << ')';
2697 unsigned NumDeclaredParams = FTy->getNumParams();
2699 CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2701 if (isStructRet) { // Skip struct return argument.
2706 bool PrintedArg = false;
2707 for (; AI != AE; ++AI, ++ArgNo) {
2708 if (PrintedArg) Out << ", ";
2709 if (ArgNo < NumDeclaredParams &&
2710 (*AI)->getType() != FTy->getParamType(ArgNo)) {
2712 printType(Out, FTy->getParamType(ArgNo),
2713 /*isSigned=*/PAL.paramHasAttr(ArgNo+1, ParamAttr::SExt));
2716 // Check if the argument is expected to be passed by value.
2717 if (I.paramHasAttr(ArgNo+1, ParamAttr::ByVal))
2718 writeOperandDeref(*AI);
2726 /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
2727 /// if the entire call is handled, return false it it wasn't handled, and
2728 /// optionally set 'WroteCallee' if the callee has already been printed out.
2729 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
2730 bool &WroteCallee) {
2733 // If this is an intrinsic that directly corresponds to a GCC
2734 // builtin, we emit it here.
2735 const char *BuiltinName = "";
2736 Function *F = I.getCalledFunction();
2737 #define GET_GCC_BUILTIN_NAME
2738 #include "llvm/Intrinsics.gen"
2739 #undef GET_GCC_BUILTIN_NAME
2740 assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2746 case Intrinsic::memory_barrier:
2747 Out << "__sync_synchronize()";
2749 case Intrinsic::vastart:
2752 Out << "va_start(*(va_list*)";
2753 writeOperand(I.getOperand(1));
2755 // Output the last argument to the enclosing function.
2756 if (I.getParent()->getParent()->arg_empty()) {
2757 cerr << "The C backend does not currently support zero "
2758 << "argument varargs functions, such as '"
2759 << I.getParent()->getParent()->getName() << "'!\n";
2762 writeOperand(--I.getParent()->getParent()->arg_end());
2765 case Intrinsic::vaend:
2766 if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2767 Out << "0; va_end(*(va_list*)";
2768 writeOperand(I.getOperand(1));
2771 Out << "va_end(*(va_list*)0)";
2774 case Intrinsic::vacopy:
2776 Out << "va_copy(*(va_list*)";
2777 writeOperand(I.getOperand(1));
2778 Out << ", *(va_list*)";
2779 writeOperand(I.getOperand(2));
2782 case Intrinsic::returnaddress:
2783 Out << "__builtin_return_address(";
2784 writeOperand(I.getOperand(1));
2787 case Intrinsic::frameaddress:
2788 Out << "__builtin_frame_address(";
2789 writeOperand(I.getOperand(1));
2792 case Intrinsic::powi:
2793 Out << "__builtin_powi(";
2794 writeOperand(I.getOperand(1));
2796 writeOperand(I.getOperand(2));
2799 case Intrinsic::setjmp:
2800 Out << "setjmp(*(jmp_buf*)";
2801 writeOperand(I.getOperand(1));
2804 case Intrinsic::longjmp:
2805 Out << "longjmp(*(jmp_buf*)";
2806 writeOperand(I.getOperand(1));
2808 writeOperand(I.getOperand(2));
2811 case Intrinsic::prefetch:
2812 Out << "LLVM_PREFETCH((const void *)";
2813 writeOperand(I.getOperand(1));
2815 writeOperand(I.getOperand(2));
2817 writeOperand(I.getOperand(3));
2820 case Intrinsic::stacksave:
2821 // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
2822 // to work around GCC bugs (see PR1809).
2823 Out << "0; *((void**)&" << GetValueName(&I)
2824 << ") = __builtin_stack_save()";
2826 case Intrinsic::dbg_stoppoint: {
2827 // If we use writeOperand directly we get a "u" suffix which is rejected
2829 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2832 << " \"" << SPI.getDirectory()
2833 << SPI.getFileName() << "\"\n";
2836 case Intrinsic::x86_sse_cmp_ss:
2837 case Intrinsic::x86_sse_cmp_ps:
2838 case Intrinsic::x86_sse2_cmp_sd:
2839 case Intrinsic::x86_sse2_cmp_pd:
2841 printType(Out, I.getType());
2843 // Multiple GCC builtins multiplex onto this intrinsic.
2844 switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
2845 default: assert(0 && "Invalid llvm.x86.sse.cmp!");
2846 case 0: Out << "__builtin_ia32_cmpeq"; break;
2847 case 1: Out << "__builtin_ia32_cmplt"; break;
2848 case 2: Out << "__builtin_ia32_cmple"; break;
2849 case 3: Out << "__builtin_ia32_cmpunord"; break;
2850 case 4: Out << "__builtin_ia32_cmpneq"; break;
2851 case 5: Out << "__builtin_ia32_cmpnlt"; break;
2852 case 6: Out << "__builtin_ia32_cmpnle"; break;
2853 case 7: Out << "__builtin_ia32_cmpord"; break;
2855 if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
2859 if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
2865 writeOperand(I.getOperand(1));
2867 writeOperand(I.getOperand(2));
2870 case Intrinsic::ppc_altivec_lvsl:
2872 printType(Out, I.getType());
2874 Out << "__builtin_altivec_lvsl(0, (void*)";
2875 writeOperand(I.getOperand(1));
2881 //This converts the llvm constraint string to something gcc is expecting.
2882 //TODO: work out platform independent constraints and factor those out
2883 // of the per target tables
2884 // handle multiple constraint codes
2885 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2887 assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2889 const char *const *table = 0;
2891 //Grab the translation table from TargetAsmInfo if it exists
2894 const TargetMachineRegistry::entry* Match =
2895 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2897 //Per platform Target Machines don't exist, so create it
2898 // this must be done only once
2899 const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2900 TAsm = TM->getTargetAsmInfo();
2904 table = TAsm->getAsmCBE();
2906 //Search the translation table if it exists
2907 for (int i = 0; table && table[i]; i += 2)
2908 if (c.Codes[0] == table[i])
2911 //default is identity
2915 //TODO: import logic from AsmPrinter.cpp
2916 static std::string gccifyAsm(std::string asmstr) {
2917 for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2918 if (asmstr[i] == '\n')
2919 asmstr.replace(i, 1, "\\n");
2920 else if (asmstr[i] == '\t')
2921 asmstr.replace(i, 1, "\\t");
2922 else if (asmstr[i] == '$') {
2923 if (asmstr[i + 1] == '{') {
2924 std::string::size_type a = asmstr.find_first_of(':', i + 1);
2925 std::string::size_type b = asmstr.find_first_of('}', i + 1);
2926 std::string n = "%" +
2927 asmstr.substr(a + 1, b - a - 1) +
2928 asmstr.substr(i + 2, a - i - 2);
2929 asmstr.replace(i, b - i + 1, n);
2932 asmstr.replace(i, 1, "%");
2934 else if (asmstr[i] == '%')//grr
2935 { asmstr.replace(i, 1, "%%"); ++i;}
2940 //TODO: assumptions about what consume arguments from the call are likely wrong
2941 // handle communitivity
2942 void CWriter::visitInlineAsm(CallInst &CI) {
2943 InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2944 std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2945 std::vector<std::pair<std::string, Value*> > Input;
2946 std::vector<std::pair<std::string, std::pair<Value*, int> > > Output;
2947 std::string Clobber;
2948 unsigned ValueCount = 0;
2950 std::vector<std::pair<Value*, int> > ResultVals;
2951 if (CI.getType() == Type::VoidTy)
2953 else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
2954 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
2955 ResultVals.push_back(std::make_pair(&CI, (int)i));
2957 ResultVals.push_back(std::make_pair(&CI, -1));
2960 for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2961 E = Constraints.end(); I != E; ++I) {
2962 assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2963 std::string C = InterpretASMConstraint(*I);
2964 if (C.empty()) continue;
2967 default: assert(0 && "Unknown asm constraint");
2968 case InlineAsm::isInput: {
2969 assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
2970 Value *V = CI.getOperand(ValueCount-ResultVals.size()+1);
2971 Input.push_back(std::make_pair(C, V));
2974 case InlineAsm::isOutput: {
2975 std::pair<Value*, int> V;
2976 if (ValueCount < ResultVals.size())
2977 V = ResultVals[ValueCount];
2979 V = std::make_pair(CI.getOperand(ValueCount-ResultVals.size()+1), -1);
2980 Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+C),
2984 case InlineAsm::isClobber:
2985 Clobber += ",\"" + C + "\"";
2986 continue; // Not an actual argument.
2988 ++ValueCount; // Consumes an argument.
2991 // Fix up the asm string for gcc.
2992 std::string asmstr = gccifyAsm(as->getAsmString());
2994 Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2996 for (unsigned i = 0, e = Output.size(); i != e; ++i) {
2999 Out << "\"" << Output[i].first << "\"("
3000 << GetValueName(Output[i].second.first);
3001 if (Output[i].second.second != -1)
3002 Out << ".field" << Output[i].second.second; // Multiple retvals.
3006 for (unsigned i = 0, e = Input.size(); i != e; ++i) {
3009 Out << "\"" << Input[i].first << "\"(";
3010 writeOperand(Input[i].second);
3014 Out << "\n :" << Clobber.substr(1);
3018 void CWriter::visitMallocInst(MallocInst &I) {
3019 assert(0 && "lowerallocations pass didn't work!");
3022 void CWriter::visitAllocaInst(AllocaInst &I) {
3024 printType(Out, I.getType());
3025 Out << ") alloca(sizeof(";
3026 printType(Out, I.getType()->getElementType());
3028 if (I.isArrayAllocation()) {
3030 writeOperand(I.getOperand(0));
3035 void CWriter::visitFreeInst(FreeInst &I) {
3036 assert(0 && "lowerallocations pass didn't work!");
3039 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
3040 gep_type_iterator E) {
3042 // If there are no indices, just print out the pointer.
3048 // Find out if the last index is into a vector. If so, we have to print this
3049 // specially. Since vectors can't have elements of indexable type, only the
3050 // last index could possibly be of a vector element.
3051 const VectorType *LastIndexIsVector = 0;
3053 for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
3054 LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
3059 // If the last index is into a vector, we can't print it as &a[i][j] because
3060 // we can't index into a vector with j in GCC. Instead, emit this as
3061 // (((float*)&a[i])+j)
3062 if (LastIndexIsVector) {
3064 printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
3070 // If the first index is 0 (very typical) we can do a number of
3071 // simplifications to clean up the code.
3072 Value *FirstOp = I.getOperand();
3073 if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
3074 // First index isn't simple, print it the hard way.
3077 ++I; // Skip the zero index.
3079 // Okay, emit the first operand. If Ptr is something that is already address
3080 // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
3081 if (isAddressExposed(Ptr)) {
3082 writeOperandInternal(Ptr);
3083 } else if (I != E && isa<StructType>(*I)) {
3084 // If we didn't already emit the first operand, see if we can print it as
3085 // P->f instead of "P[0].f"
3087 Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3088 ++I; // eat the struct index as well.
3090 // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
3097 for (; I != E; ++I) {
3098 if (isa<StructType>(*I)) {
3099 Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
3100 } else if (!isa<VectorType>(*I)) {
3102 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3105 // If the last index is into a vector, then print it out as "+j)". This
3106 // works with the 'LastIndexIsVector' code above.
3107 if (isa<Constant>(I.getOperand()) &&
3108 cast<Constant>(I.getOperand())->isNullValue()) {
3109 Out << "))"; // avoid "+0".
3112 writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
3120 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
3121 bool IsVolatile, unsigned Alignment) {
3123 bool IsUnaligned = Alignment &&
3124 Alignment < TD->getABITypeAlignment(OperandType);
3128 if (IsVolatile || IsUnaligned) {
3131 Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
3132 printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
3135 if (IsVolatile) Out << "volatile ";
3141 writeOperand(Operand);
3143 if (IsVolatile || IsUnaligned) {
3150 void CWriter::visitLoadInst(LoadInst &I) {
3151 writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
3156 void CWriter::visitStoreInst(StoreInst &I) {
3157 writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
3158 I.isVolatile(), I.getAlignment());
3160 Value *Operand = I.getOperand(0);
3161 Constant *BitMask = 0;
3162 if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
3163 if (!ITy->isPowerOf2ByteWidth())
3164 // We have a bit width that doesn't match an even power-of-2 byte
3165 // size. Consequently we must & the value with the type's bit mask
3166 BitMask = ConstantInt::get(ITy, ITy->getBitMask());
3169 writeOperand(Operand);
3172 printConstant(BitMask);
3177 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
3178 printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
3182 void CWriter::visitVAArgInst(VAArgInst &I) {
3183 Out << "va_arg(*(va_list*)";
3184 writeOperand(I.getOperand(0));
3186 printType(Out, I.getType());
3190 void CWriter::visitInsertElementInst(InsertElementInst &I) {
3191 const Type *EltTy = I.getType()->getElementType();
3192 writeOperand(I.getOperand(0));
3195 printType(Out, PointerType::getUnqual(EltTy));
3196 Out << ")(&" << GetValueName(&I) << "))[";
3197 writeOperand(I.getOperand(2));
3199 writeOperand(I.getOperand(1));
3203 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
3204 // We know that our operand is not inlined.
3207 cast<VectorType>(I.getOperand(0)->getType())->getElementType();
3208 printType(Out, PointerType::getUnqual(EltTy));
3209 Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
3210 writeOperand(I.getOperand(1));
3214 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
3216 printType(Out, SVI.getType());
3218 const VectorType *VT = SVI.getType();
3219 unsigned NumElts = VT->getNumElements();
3220 const Type *EltTy = VT->getElementType();
3222 for (unsigned i = 0; i != NumElts; ++i) {
3224 int SrcVal = SVI.getMaskValue(i);
3225 if ((unsigned)SrcVal >= NumElts*2) {
3226 Out << " 0/*undef*/ ";
3228 Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
3229 if (isa<Instruction>(Op)) {
3230 // Do an extractelement of this value from the appropriate input.
3232 printType(Out, PointerType::getUnqual(EltTy));
3233 Out << ")(&" << GetValueName(Op)
3234 << "))[" << (SrcVal & (NumElts-1)) << "]";
3235 } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
3238 printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
3246 void CWriter::visitGetResultInst(GetResultInst &GRI) {
3248 if (isa<UndefValue>(GRI.getOperand(0))) {
3250 printType(Out, GRI.getType());
3251 Out << ") 0/*UNDEF*/";
3253 Out << GetValueName(GRI.getOperand(0)) << ".field" << GRI.getIndex();
3258 //===----------------------------------------------------------------------===//
3259 // External Interface declaration
3260 //===----------------------------------------------------------------------===//
3262 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
3264 CodeGenFileType FileType,
3266 if (FileType != TargetMachine::AssemblyFile) return true;
3268 PM.add(createGCLoweringPass());
3269 PM.add(createLowerAllocationsPass(true));
3270 PM.add(createLowerInvokePass());
3271 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
3272 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
3273 PM.add(new CWriter(o));
3274 PM.add(createCollectorMetadataDeleter());