#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
+#include "llvm/ParameterAttributes.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
-#include "llvm/SymbolTable.h"
#include "llvm/TypeSymbolTable.h"
#include "llvm/Intrinsics.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Target/TargetAsmInfo.h"
+#include "llvm/Target/TargetData.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
/// external functions with the same name.
///
class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
+ public:
+ static char ID;
+ CBackendNameAllUsedStructsAndMergeFunctions()
+ : ModulePass((intptr_t)&ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<FindUsedTypes>();
}
virtual bool runOnModule(Module &M);
};
+ char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
+
/// CWriter - This class is the main chunk of code that converts an LLVM
/// module to a C translation unit.
class CWriter : public FunctionPass, public InstVisitor<CWriter> {
std::ostream &Out;
- IntrinsicLowering IL;
+ IntrinsicLowering *IL;
Mangler *Mang;
LoopInfo *LI;
const Module *TheModule;
const TargetAsmInfo* TAsm;
+ const TargetData* TD;
std::map<const Type *, std::string> TypeNames;
-
std::map<const ConstantFP *, unsigned> FPConstantMap;
+ std::set<Function*> intrinsicPrototypesAlreadyGenerated;
+
public:
- CWriter(std::ostream &o) : Out(o), TAsm(0) {}
+ static char ID;
+ CWriter(std::ostream &o)
+ : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0),
+ TheModule(0), TAsm(0), TD(0) {}
virtual const char *getPassName() const { return "C backend"; }
// Output all floating point constants that cannot be printed accurately.
printFloatingPointConstants(F);
- // Ensure that no local symbols conflict with global symbols.
- F.renameLocalSymbols();
-
printFunction(F);
FPConstantMap.clear();
return false;
bool isSigned = false,
const std::string &VariableName = "",
bool IgnoreName = false);
- std::ostream &printPrimitiveType(std::ostream &Out, const Type *Ty,
+ std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
bool isSigned,
const std::string &NameSoFar = "");
void printConstantWithCast(Constant *CPV, unsigned Opcode);
bool printConstExprCast(const ConstantExpr *CE);
void printConstantArray(ConstantArray *CPA);
- void printConstantPacked(ConstantPacked *CP);
+ void printConstantVector(ConstantVector *CP);
// isInlinableInst - Attempt to inline instructions into their uses to build
// trees as much as possible. To do this, we have to consistently decide
void visitSelectInst(SelectInst &I);
void visitCallInst (CallInst &I);
void visitInlineAsm(CallInst &I);
- void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
void visitMallocInst(MallocInst &I);
void visitAllocaInst(AllocaInst &I);
}
void outputLValue(Instruction *I) {
- Out << " " << Mang->getValueName(I) << " = ";
+ Out << " " << GetValueName(I) << " = ";
}
bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
unsigned Indent);
void printIndexingExpression(Value *Ptr, gep_type_iterator I,
gep_type_iterator E);
+
+ std::string GetValueName(const Value *Operand);
};
}
+char CWriter::ID = 0;
+
/// This method inserts names for any unnamed structure types that are used by
/// the program, and removes names from structure types that are not used by the
/// program.
for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
TI != TE; ) {
TypeSymbolTable::iterator I = TI++;
-
- // If this is not used, remove it from the symbol table.
- std::set<const Type *>::iterator UTI = UT.find(I->second);
- if (UTI == UT.end())
+
+ // If this isn't a struct type, remove it from our set of types to name.
+ // This simplifies emission later.
+ if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
TST.remove(I);
- else
- UT.erase(UTI); // Only keep one name for this type.
+ } else {
+ // If this is not used, remove it from the symbol table.
+ std::set<const Type *>::iterator UTI = UT.find(I->second);
+ if (UTI == UT.end())
+ TST.remove(I);
+ else
+ UT.erase(UTI); // Only keep one name for this type.
+ }
}
// UT now contains types that are not named. Loop over it, naming
std::map<std::string, GlobalValue*> ExtSymbols;
for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
Function *GV = I++;
- if (GV->isExternal() && GV->hasName()) {
+ if (GV->isDeclaration() && GV->hasName()) {
std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
= ExtSymbols.insert(std::make_pair(GV->getName(), GV));
if (!X.second) {
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E;) {
GlobalVariable *GV = I++;
- if (GV->isExternal() && GV->hasName()) {
+ if (GV->isDeclaration() && GV->hasName()) {
std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
= ExtSymbols.insert(std::make_pair(GV->getName(), GV));
if (!X.second) {
FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
const Type *RetTy = cast<PointerType>(I->get())->getElementType();
unsigned Idx = 1;
+ const ParamAttrsList *Attrs = FTy->getParamAttrs();
for (++I; I != E; ++I) {
if (PrintedType)
FunctionInnards << ", ";
printType(FunctionInnards, *I,
- /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
+ /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
PrintedType = true;
}
if (FTy->isVarArg()) {
FunctionInnards << ')';
std::string tstr = FunctionInnards.str();
printType(Out, RetTy,
- /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
+ /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
}
std::ostream &
-CWriter::printPrimitiveType(std::ostream &Out, const Type *Ty, bool isSigned,
+CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
const std::string &NameSoFar) {
- assert(Ty->isPrimitiveType() && "Invalid type for printPrimitiveType");
+ assert((Ty->isPrimitiveType() || Ty->isInteger()) &&
+ "Invalid type for printSimpleType");
switch (Ty->getTypeID()) {
- case Type::VoidTyID: return Out << "void " << NameSoFar;
- case Type::BoolTyID: return Out << "bool " << NameSoFar;
- case Type::Int8TyID:
- return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
- case Type::Int16TyID:
- return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
- case Type::Int32TyID:
- return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
- case Type::Int64TyID:
- return Out << (isSigned?"signed":"unsigned") << " long long " << NameSoFar;
- case Type::FloatTyID: return Out << "float " << NameSoFar;
- case Type::DoubleTyID: return Out << "double " << NameSoFar;
+ case Type::VoidTyID: return Out << "void " << NameSoFar;
+ case Type::IntegerTyID: {
+ unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
+ if (NumBits == 1)
+ return Out << "bool " << NameSoFar;
+ else if (NumBits <= 8)
+ return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
+ else if (NumBits <= 16)
+ return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
+ else if (NumBits <= 32)
+ return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
+ else {
+ assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
+ return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
+ }
+ }
+ case Type::FloatTyID: return Out << "float " << NameSoFar;
+ case Type::DoubleTyID: return Out << "double " << NameSoFar;
default :
cerr << "Unknown primitive type: " << *Ty << "\n";
abort();
std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
bool isSigned, const std::string &NameSoFar,
bool IgnoreName) {
- if (Ty->isPrimitiveType()) {
- // FIXME:Signedness. When integer types are signless, this should just
- // always pass "false" for the sign of the primitive type. The instructions
- // will figure out how the value is to be interpreted.
- printPrimitiveType(Out, Ty, isSigned, NameSoFar);
+ if (Ty->isPrimitiveType() || Ty->isInteger()) {
+ printSimpleType(Out, Ty, isSigned, NameSoFar);
return Out;
}
const FunctionType *FTy = cast<FunctionType>(Ty);
std::stringstream FunctionInnards;
FunctionInnards << " (" << NameSoFar << ") (";
+ const ParamAttrsList *Attrs = FTy->getParamAttrs();
unsigned Idx = 1;
for (FunctionType::param_iterator I = FTy->param_begin(),
E = FTy->param_end(); I != E; ++I) {
if (I != FTy->param_begin())
FunctionInnards << ", ";
printType(FunctionInnards, *I,
- /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
+ /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
++Idx;
}
if (FTy->isVarArg()) {
FunctionInnards << ')';
std::string tstr = FunctionInnards.str();
printType(Out, FTy->getReturnType(),
- /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
+ /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
return Out;
}
case Type::StructTyID: {
printType(Out, *I, false, "field" + utostr(Idx++));
Out << ";\n";
}
- return Out << '}';
+ Out << '}';
+ if (STy->isPacked())
+ Out << " __attribute__ ((packed))";
+ return Out;
}
case Type::PointerTyID: {
std::string ptrName = "*" + NameSoFar;
if (isa<ArrayType>(PTy->getElementType()) ||
- isa<PackedType>(PTy->getElementType()))
+ isa<VectorType>(PTy->getElementType()))
ptrName = "(" + ptrName + ")";
return printType(Out, PTy->getElementType(), false, ptrName);
NameSoFar + "[" + utostr(NumElements) + "]");
}
- case Type::PackedTyID: {
- const PackedType *PTy = cast<PackedType>(Ty);
+ case Type::VectorTyID: {
+ const VectorType *PTy = cast<VectorType>(Ty);
unsigned NumElements = PTy->getNumElements();
if (NumElements == 0) NumElements = 1;
return printType(Out, PTy->getElementType(), false,
}
}
-void CWriter::printConstantPacked(ConstantPacked *CP) {
+void CWriter::printConstantVector(ConstantVector *CP) {
Out << '{';
if (CP->getNumOperands()) {
Out << ' ';
// only deal in IEEE FP).
//
static bool isFPCSafeToPrint(const ConstantFP *CFP) {
+ APFloat APF = APFloat(CFP->getValueAPF()); // copy
+ if (CFP->getType()==Type::FloatTy)
+ APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
char Buffer[100];
- sprintf(Buffer, "%a", CFP->getValue());
-
+ sprintf(Buffer, "%a", APF.convertToDouble());
if (!strncmp(Buffer, "0x", 2) ||
!strncmp(Buffer, "-0x", 3) ||
!strncmp(Buffer, "+0x", 3))
- return atof(Buffer) == CFP->getValue();
+ return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
return false;
#else
- std::string StrVal = ftostr(CFP->getValue());
+ std::string StrVal = ftostr(APF);
while (StrVal[0] == ' ')
StrVal.erase(StrVal.begin());
((StrVal[0] == '-' || StrVal[0] == '+') &&
(StrVal[1] >= '0' && StrVal[1] <= '9')))
// Reparse stringized version!
- return atof(StrVal.c_str()) == CFP->getValue();
+ return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
return false;
#endif
}
case Instruction::PtrToInt:
case Instruction::FPToUI: // For these, make sure we get an unsigned dest
Out << '(';
- printPrimitiveType(Out, DstTy, false);
+ printSimpleType(Out, DstTy, false);
Out << ')';
break;
case Instruction::SExt:
case Instruction::FPToSI: // For these, make sure we get a signed dest
Out << '(';
- printPrimitiveType(Out, DstTy, true);
+ printSimpleType(Out, DstTy, true);
Out << ')';
break;
default:
case Instruction::UIToFP:
case Instruction::ZExt:
Out << '(';
- printPrimitiveType(Out, SrcTy, false);
+ printSimpleType(Out, SrcTy, false);
Out << ')';
break;
case Instruction::SIToFP:
case Instruction::SExt:
Out << '(';
- printPrimitiveType(Out, SrcTy, true);
+ printSimpleType(Out, SrcTy, true);
Out << ')';
break;
case Instruction::IntToPtr:
Out << "(";
printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
if (CE->getOpcode() == Instruction::SExt &&
- CE->getOperand(0)->getType() == Type::BoolTy) {
+ CE->getOperand(0)->getType() == Type::Int1Ty) {
// Make sure we really sext from bool here by subtracting from 0
Out << "0-";
}
printConstant(CE->getOperand(0));
- if (CE->getType() == Type::BoolTy &&
+ if (CE->getType() == Type::Int1Ty &&
(CE->getOpcode() == Instruction::Trunc ||
CE->getOpcode() == Instruction::FPToUI ||
CE->getOpcode() == Instruction::FPToSI ||
return;
}
- if (ConstantBool *CB = dyn_cast<ConstantBool>(CPV)) {
- Out << (CB->getValue() ? '1' : '0') ;
- return;
- }
-
if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
const Type* Ty = CI->getType();
- Out << "((";
- printPrimitiveType(Out, Ty, false) << ')';
- if (CI->isMinValue(true))
- Out << CI->getZExtValue() << 'u';
- else
- Out << CI->getSExtValue();
- if (Ty->getPrimitiveSizeInBits() > 32)
- Out << "ll";
- Out << ')';
+ if (Ty == Type::Int1Ty)
+ Out << (CI->getZExtValue() ? '1' : '0') ;
+ else {
+ Out << "((";
+ printSimpleType(Out, Ty, false) << ')';
+ if (CI->isMinValue(true))
+ Out << CI->getZExtValue() << 'u';
+ else
+ Out << CI->getSExtValue();
+ if (Ty->getPrimitiveSizeInBits() > 32)
+ Out << "ll";
+ Out << ')';
+ }
return;
}
Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
<< "*)&FPConstant" << I->second << ')';
} else {
- if (IsNAN(FPC->getValue())) {
+ double V = FPC->getType() == Type::FloatTy ?
+ FPC->getValueAPF().convertToFloat() :
+ FPC->getValueAPF().convertToDouble();
+ if (IsNAN(V)) {
// The value is NaN
+ // FIXME the actual NaN bits should be emitted.
// The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
// it's 0x7ff4.
const unsigned long QuietNaN = 0x7ff8UL;
// We need to grab the first part of the FP #
char Buffer[100];
- uint64_t ll = DoubleToBits(FPC->getValue());
+ uint64_t ll = DoubleToBits(V);
sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
std::string Num(&Buffer[0], &Buffer[6]);
else
Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
<< Buffer << "\") /*nan*/ ";
- } else if (IsInf(FPC->getValue())) {
+ } else if (IsInf(V)) {
// The value is Inf
- if (FPC->getValue() < 0) Out << '-';
+ if (V < 0) Out << '-';
Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
<< " /*inf*/ ";
} else {
#if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
// Print out the constant as a floating point number.
char Buffer[100];
- sprintf(Buffer, "%a", FPC->getValue());
+ sprintf(Buffer, "%a", V);
Num = Buffer;
#else
- Num = ftostr(FPC->getValue());
+ Num = ftostr(FPC->getValueAPF());
#endif
- Out << Num;
+ Out << Num;
}
}
break;
}
break;
- case Type::PackedTyID:
+ case Type::VectorTyID:
if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
- const PackedType *AT = cast<PackedType>(CPV->getType());
+ const VectorType *AT = cast<VectorType>(CPV->getType());
Out << '{';
if (AT->getNumElements()) {
Out << ' ';
}
Out << " }";
} else {
- printConstantPacked(cast<ConstantPacked>(CPV));
+ printConstantVector(cast<ConstantVector>(CPV));
}
break;
}
if (NeedsExplicitCast) {
Out << "((";
- if (Ty->isInteger())
- printPrimitiveType(Out, Ty, TypeIsSigned);
+ if (Ty->isInteger() && Ty != Type::Int1Ty)
+ printSimpleType(Out, Ty, TypeIsSigned);
else
printType(Out, Ty); // not integer, sign doesn't matter
Out << ")(";
// operand.
if (shouldCast) {
Out << "((";
- printPrimitiveType(Out, OpTy, typeIsSigned);
+ printSimpleType(Out, OpTy, typeIsSigned);
Out << ")";
printConstant(CPV);
Out << ")";
printConstant(CPV);
}
+std::string CWriter::GetValueName(const Value *Operand) {
+ std::string Name;
+
+ if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
+ std::string VarName;
+
+ Name = Operand->getName();
+ VarName.reserve(Name.capacity());
+
+ for (std::string::iterator I = Name.begin(), E = Name.end();
+ I != E; ++I) {
+ char ch = *I;
+
+ if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
+ (ch >= '0' && ch <= '9') || ch == '_'))
+ VarName += '_';
+ else
+ VarName += ch;
+ }
+
+ Name = "llvm_cbe_" + VarName;
+ } else {
+ Name = Mang->getValueName(Operand);
+ }
+
+ return Name;
+}
+
void CWriter::writeOperandInternal(Value *Operand) {
if (Instruction *I = dyn_cast<Instruction>(Operand))
if (isInlinableInst(*I) && !isDirectAlloca(I)) {
}
Constant* CPV = dyn_cast<Constant>(Operand);
- if (CPV && !isa<GlobalValue>(CPV)) {
+
+ if (CPV && !isa<GlobalValue>(CPV))
printConstant(CPV);
- } else {
- Out << Mang->getValueName(Operand);
- }
+ else
+ Out << GetValueName(Operand);
}
void CWriter::writeOperandRaw(Value *Operand) {
if (CPV && !isa<GlobalValue>(CPV)) {
printConstant(CPV);
} else {
- Out << Mang->getValueName(Operand);
+ Out << GetValueName(Operand);
}
}
case Instruction::URem:
case Instruction::UDiv:
Out << "((";
- printPrimitiveType(Out, Ty, false);
+ printSimpleType(Out, Ty, false);
Out << ")(";
return true;
case Instruction::AShr:
case Instruction::SRem:
case Instruction::SDiv:
Out << "((";
- printPrimitiveType(Out, Ty, true);
+ printSimpleType(Out, Ty, true);
Out << ")(";
return true;
default: break;
// operand.
if (shouldCast) {
Out << "((";
- printPrimitiveType(Out, OpTy, castIsSigned);
+ printSimpleType(Out, OpTy, castIsSigned);
Out << ")";
writeOperand(Operand);
Out << ")";
// operand.
if (shouldCast) {
Out << "((";
- if (OpTy->isInteger())
- printPrimitiveType(Out, OpTy, castIsSigned);
+ if (OpTy->isInteger() && OpTy != Type::Int1Ty)
+ printSimpleType(Out, OpTy, castIsSigned);
else
printType(Out, OpTy); // not integer, sign doesn't matter
Out << ")";
// Alloca is hard to get, and we don't want to include stdlib.h here.
Out << "/* get a declaration for alloca */\n"
<< "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
- << "extern void *_alloca(unsigned long);\n"
- << "#define alloca(x) _alloca(x)\n"
+ << "#define alloca(x) __builtin_alloca((x))\n"
+ << "#define _alloca(x) __builtin_alloca((x))\n"
<< "#elif defined(__APPLE__)\n"
<< "extern void *__builtin_alloca(unsigned long);\n"
<< "#define alloca(x) __builtin_alloca(x)\n"
<< "#define alloca(x) __builtin_alloca(x)\n"
<< "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
<< "#define alloca(x) __builtin_alloca(x)\n"
- << "#elif !defined(_MSC_VER)\n"
+ << "#elif defined(_MSC_VER)\n"
+ << "#define inline _inline\n"
+ << "#define alloca(x) _alloca(x)\n"
+ << "#else\n"
<< "#include <alloca.h>\n"
<< "#endif\n\n";
<< "#define __ATTRIBUTE_WEAK__\n"
<< "#endif\n\n";
+ // Add hidden visibility support. FIXME: APPLE_CC?
+ Out << "#if defined(__GNUC__)\n"
+ << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
+ << "#endif\n\n";
+
// Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
// From the GCC documentation:
//
<< "#define __ATTRIBUTE_DTOR__\n"
<< "#define LLVM_ASM(X)\n"
<< "#endif\n\n";
+
+ Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
+ << "#define __builtin_stack_save() 0 /* not implemented */\n"
+ << "#define __builtin_stack_restore(X) /* noop */\n"
+ << "#endif\n\n";
// Output target-specific code that should be inserted into main.
Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
- // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
- Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
- << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
- << "defined(__x86_64__)\n"
- << "#undef CODE_FOR_MAIN\n"
- << "#define CODE_FOR_MAIN() \\\n"
- << " {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
- << " F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
- << "#endif\n#endif\n";
-
}
/// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
// Initialize
TheModule = &M;
- IL.AddPrototypes(M);
+ TD = new TargetData(&M);
+ IL = new IntrinsicLowering(*TD);
+ IL->AddPrototypes(M);
// Ensure that all structure types have names...
Mang = new Mangler(M);
Out << "\n/* External Global Variable Declarations */\n";
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) {
- if (I->hasExternalLinkage()) {
+
+ if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
Out << "extern ";
- printType(Out, I->getType()->getElementType(), false,
- Mang->getValueName(I));
- Out << ";\n";
- } else if (I->hasDLLImportLinkage()) {
+ else if (I->hasDLLImportLinkage())
Out << "__declspec(dllimport) ";
- printType(Out, I->getType()->getElementType(), false,
- Mang->getValueName(I));
- Out << ";\n";
- } else if (I->hasExternalWeakLinkage()) {
- Out << "extern ";
- printType(Out, I->getType()->getElementType(), false,
- Mang->getValueName(I));
- Out << " __EXTERNAL_WEAK__ ;\n";
- }
+ else
+ continue; // Internal Global
+
+ // Thread Local Storage
+ if (I->isThreadLocal())
+ Out << "__thread ";
+
+ printType(Out, I->getType()->getElementType(), false, GetValueName(I));
+
+ if (I->hasExternalWeakLinkage())
+ Out << " __EXTERNAL_WEAK__";
+ Out << ";\n";
}
}
Out << " __ATTRIBUTE_CTOR__";
if (StaticDtors.count(I))
Out << " __ATTRIBUTE_DTOR__";
+ if (I->hasHiddenVisibility())
+ Out << " __HIDDEN__";
if (I->hasName() && I->getName()[0] == 1)
Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
Out << "\n\n/* Global Variable Declarations */\n";
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
- if (!I->isExternal()) {
+ if (!I->isDeclaration()) {
// Ignore special globals, such as debug info.
if (getGlobalVariableClass(I))
continue;
-
+
if (I->hasInternalLinkage())
Out << "static ";
else
Out << "extern ";
+
+ // Thread Local Storage
+ if (I->isThreadLocal())
+ Out << "__thread ";
+
printType(Out, I->getType()->getElementType(), false,
- Mang->getValueName(I));
+ GetValueName(I));
if (I->hasLinkOnceLinkage())
Out << " __attribute__((common))";
Out << " __ATTRIBUTE_WEAK__";
else if (I->hasExternalWeakLinkage())
Out << " __EXTERNAL_WEAK__";
+ if (I->hasHiddenVisibility())
+ Out << " __HIDDEN__";
Out << ";\n";
}
}
Out << "\n\n/* Global Variable Definitions and Initialization */\n";
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
- if (!I->isExternal()) {
+ if (!I->isDeclaration()) {
// Ignore special globals, such as debug info.
if (getGlobalVariableClass(I))
continue;
-
+
if (I->hasInternalLinkage())
Out << "static ";
else if (I->hasDLLImportLinkage())
Out << "__declspec(dllimport) ";
else if (I->hasDLLExportLinkage())
Out << "__declspec(dllexport) ";
-
+
+ // Thread Local Storage
+ if (I->isThreadLocal())
+ Out << "__thread ";
+
printType(Out, I->getType()->getElementType(), false,
- Mang->getValueName(I));
+ GetValueName(I));
if (I->hasLinkOnceLinkage())
Out << " __attribute__((common))";
else if (I->hasWeakLinkage())
Out << " __ATTRIBUTE_WEAK__";
+ if (I->hasHiddenVisibility())
+ Out << " __HIDDEN__";
+
// If the initializer is not null, emit the initializer. If it is null,
// we try to avoid emitting large amounts of zeros. The problem with
// this, however, occurs when the variable has weak linkage. In this
Out << " = " ;
if (isa<StructType>(I->getInitializer()->getType()) ||
isa<ArrayType>(I->getInitializer()->getType()) ||
- isa<PackedType>(I->getInitializer()->getType())) {
+ isa<VectorType>(I->getInitializer()->getType())) {
Out << "{ 0 }";
} else {
// Just print it out normally.
if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
!FPConstantMap.count(FPC)) {
- double Val = FPC->getValue();
-
FPConstantMap[FPC] = FPCounter; // Number the FP constants
if (FPC->getType() == Type::DoubleTy) {
+ double Val = FPC->getValueAPF().convertToDouble();
Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
<< " = 0x" << std::hex << DoubleToBits(Val) << std::dec
<< "ULL; /* " << Val << " */\n";
} else if (FPC->getType() == Type::FloatTy) {
+ float Val = FPC->getValueAPF().convertToFloat();
Out << "static const ConstantFloatTy FPConstant" << FPCounter++
<< " = 0x" << std::hex << FloatToBits(Val) << std::dec
<< "U; /* " << Val << " */\n";
// Print out forward declarations for structure types before anything else!
Out << "/* Structure forward decls */\n";
- for (; I != End; ++I)
- if (const Type *STy = dyn_cast<StructType>(I->second)) {
- std::string Name = "struct l_" + Mang->makeNameProper(I->first);
- Out << Name << ";\n";
- TypeNames.insert(std::make_pair(STy, Name));
- }
+ for (; I != End; ++I) {
+ std::string Name = "struct l_" + Mang->makeNameProper(I->first);
+ Out << Name << ";\n";
+ TypeNames.insert(std::make_pair(I->second, Name));
+ }
Out << '\n';
- // Now we can print out typedefs...
+ // Now we can print out typedefs. Above, we guaranteed that this can only be
+ // for struct or opaque types.
Out << "/* Typedefs */\n";
for (I = TST.begin(); I != End; ++I) {
- const Type *Ty = cast<Type>(I->second);
std::string Name = "l_" + Mang->makeNameProper(I->first);
Out << "typedef ";
- printType(Out, Ty, false, Name);
+ printType(Out, I->second, false, Name);
Out << ";\n";
}
// Push the struct onto the stack and recursively push all structs
// this one depends on.
//
-// TODO: Make this work properly with packed types
+// TODO: Make this work properly with vector types
//
void CWriter::printContainedStructs(const Type *Ty,
std::set<const StructType*> &StructPrinted){
// Don't walk through pointers.
- if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
+ if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
// Print all contained types first.
for (Type::subtype_iterator I = Ty->subtype_begin(),
}
void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
- /// isCStructReturn - Should this function actually return a struct by-value?
- bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
+ /// isStructReturn - Should this function actually return a struct by-value?
+ bool isStructReturn = F->getFunctionType()->isStructReturn();
if (F->hasInternalLinkage()) Out << "static ";
if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
// Loop over the arguments, printing them...
const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
+ const ParamAttrsList *Attrs = FT->getParamAttrs();
std::stringstream FunctionInnards;
// Print out the name...
- FunctionInnards << Mang->getValueName(F) << '(';
+ FunctionInnards << GetValueName(F) << '(';
bool PrintedArg = false;
- if (!F->isExternal()) {
+ if (!F->isDeclaration()) {
if (!F->arg_empty()) {
Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
// If this is a struct-return function, don't print the hidden
// struct-return argument.
- if (isCStructReturn) {
+ if (isStructReturn) {
assert(I != E && "Invalid struct return function!");
++I;
}
for (; I != E; ++I) {
if (PrintedArg) FunctionInnards << ", ";
if (I->hasName() || !Prototype)
- ArgName = Mang->getValueName(I);
+ ArgName = GetValueName(I);
else
ArgName = "";
printType(FunctionInnards, I->getType(),
- /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute),
+ /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt),
ArgName);
PrintedArg = true;
++Idx;
// If this is a struct-return function, don't print the hidden
// struct-return argument.
- if (isCStructReturn) {
+ if (isStructReturn) {
assert(I != E && "Invalid struct return function!");
++I;
}
for (; I != E; ++I) {
if (PrintedArg) FunctionInnards << ", ";
printType(FunctionInnards, *I,
- /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute));
+ /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
PrintedArg = true;
++Idx;
}
// Get the return tpe for the function.
const Type *RetTy;
- if (!isCStructReturn)
+ if (!isStructReturn)
RetTy = F->getReturnType();
else {
// If this is a struct-return function, print the struct-return type.
// Print out the return type and the signature built above.
printType(Out, RetTy,
- /*isSigned=*/FT->paramHasAttr(0, FunctionType::SExtAttribute),
+ /*isSigned=*/ Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
FunctionInnards.str());
}
}
void CWriter::printFunction(Function &F) {
+ /// isStructReturn - Should this function actually return a struct by-value?
+ bool isStructReturn = F.getFunctionType()->isStructReturn();
+
printFunctionSignature(&F, false);
Out << " {\n";
// If this is a struct return function, handle the result with magic.
- if (F.getCallingConv() == CallingConv::CSRet) {
+ if (isStructReturn) {
const Type *StructTy =
cast<PointerType>(F.arg_begin()->getType())->getElementType();
Out << " ";
Out << " ";
printType(Out, F.arg_begin()->getType(), false,
- Mang->getValueName(F.arg_begin()));
+ GetValueName(F.arg_begin()));
Out << " = &StructReturn;\n";
}
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
if (const AllocaInst *AI = isDirectAlloca(&*I)) {
Out << " ";
- printType(Out, AI->getAllocatedType(), false, Mang->getValueName(AI));
+ printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
Out << "; /* Address-exposed local */\n";
PrintedVar = true;
} else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
Out << " ";
- printType(Out, I->getType(), false, Mang->getValueName(&*I));
+ printType(Out, I->getType(), false, GetValueName(&*I));
Out << ";\n";
if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
Out << " ";
printType(Out, I->getType(), false,
- Mang->getValueName(&*I)+"__PHI_TEMPORARY");
+ GetValueName(&*I)+"__PHI_TEMPORARY");
Out << ";\n";
}
PrintedVar = true;
// of a union to do the BitCast. This is separate from the need for a
// variable to hold the result of the BitCast.
if (isFPIntBitCast(*I)) {
- Out << " llvmBitCastUnion " << Mang->getValueName(&*I)
+ Out << " llvmBitCastUnion " << GetValueName(&*I)
<< "__BITCAST_TEMPORARY;\n";
PrintedVar = true;
}
break;
}
- if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
+ if (NeedsLabel) Out << GetValueName(BB) << ":\n";
// Output all of the instructions in the basic block...
for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
//
void CWriter::visitReturnInst(ReturnInst &I) {
// If this is a struct return function, return the temporary struct.
- if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
+ bool isStructReturn = I.getParent()->getParent()->
+ getFunctionType()->isStructReturn();
+
+ if (isStructReturn) {
Out << " return StructReturn;\n";
return;
}
Value *IV = PN->getIncomingValueForBlock(CurBlock);
if (!isa<UndefValue>(IV)) {
Out << std::string(Indent, ' ');
- Out << " " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
+ Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
writeOperand(IV);
Out << "; /* for PHI node */\n";
}
writeOperandWithCast(I.getOperand(0), I.getOpcode());
switch (I.getOpcode()) {
- case Instruction::Add: Out << " + "; break;
- case Instruction::Sub: Out << " - "; break;
- case Instruction::Mul: Out << '*'; break;
+ case Instruction::Add: Out << " + "; break;
+ case Instruction::Sub: Out << " - "; break;
+ case Instruction::Mul: Out << " * "; break;
case Instruction::URem:
case Instruction::SRem:
- case Instruction::FRem: Out << '%'; break;
+ case Instruction::FRem: Out << " % "; break;
case Instruction::UDiv:
case Instruction::SDiv:
- case Instruction::FDiv: Out << '/'; break;
- case Instruction::And: Out << " & "; break;
- case Instruction::Or: Out << " | "; break;
- case Instruction::Xor: Out << " ^ "; break;
+ case Instruction::FDiv: Out << " / "; break;
+ case Instruction::And: Out << " & "; break;
+ case Instruction::Or: Out << " | "; break;
+ case Instruction::Xor: Out << " ^ "; break;
case Instruction::Shl : Out << " << "; break;
case Instruction::LShr:
case Instruction::AShr: Out << " >> "; break;
switch (Ty->getTypeID()) {
default: assert(0 && "Invalid Type");
case Type::FloatTyID: return "Float";
- case Type::Int32TyID: return "Int32";
case Type::DoubleTyID: return "Double";
- case Type::Int64TyID: return "Int64";
+ case Type::IntegerTyID: {
+ unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
+ if (NumBits <= 32)
+ return "Int32";
+ else
+ return "Int64";
+ }
}
}
Out << '(';
if (isFPIntBitCast(I)) {
// These int<->float and long<->double casts need to be handled specially
- Out << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
+ Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
<< getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
writeOperand(I.getOperand(0));
- Out << ", " << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
+ Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
<< getFloatBitCastField(I.getType());
} else {
printCast(I.getOpcode(), SrcTy, DstTy);
- if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
+ if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
// Make sure we really get a sext from bool by subtracing the bool from 0
Out << "0-";
}
writeOperand(I.getOperand(0));
- if (DstTy == Type::BoolTy &&
+ if (DstTy == Type::Int1Ty &&
(I.getOpcode() == Instruction::Trunc ||
I.getOpcode() == Instruction::FPToUI ||
I.getOpcode() == Instruction::FPToSI ||
void CWriter::lowerIntrinsics(Function &F) {
- for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
+ // This is used to keep track of intrinsics that get generated to a lowered
+ // function. We must generate the prototypes before the function body which
+ // will only be expanded on first use (by the loop below).
+ std::vector<Function*> prototypesToGen;
+
+ // Examine all the instructions in this function to find the intrinsics that
+ // need to be lowered.
+ for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(I++))
if (Function *F = CI->getCalledFunction())
if (CI != &BB->front())
Before = prior(BasicBlock::iterator(CI));
- IL.LowerIntrinsicCall(CI);
+ IL->LowerIntrinsicCall(CI);
if (Before) { // Move iterator to instruction after call
I = Before; ++I;
} else {
I = BB->begin();
}
+ // If the intrinsic got lowered to another call, and that call has
+ // a definition then we need to make sure its prototype is emitted
+ // before any calls to it.
+ if (CallInst *Call = dyn_cast<CallInst>(I))
+ if (Function *NewF = Call->getCalledFunction())
+ if (!NewF->isDeclaration())
+ prototypesToGen.push_back(NewF);
+
break;
}
-}
+ // We may have collected some prototypes to emit in the loop above.
+ // Emit them now, before the function that uses them is emitted. But,
+ // be careful not to emit them twice.
+ std::vector<Function*>::iterator I = prototypesToGen.begin();
+ std::vector<Function*>::iterator E = prototypesToGen.end();
+ for ( ; I != E; ++I) {
+ if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
+ Out << '\n';
+ printFunctionSignature(*I, true);
+ Out << ";\n";
+ }
+ }
+}
void CWriter::visitCallInst(CallInst &I) {
Value *Callee = I.getCalledValue();
+ const PointerType *PTy = cast<PointerType>(Callee->getType());
+ const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
+
// If this is a call to a struct-return function, assign to the first
// parameter instead of passing it to the call.
- bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
+ bool isStructRet = FTy->isStructReturn();
if (isStructRet) {
Out << "*(";
writeOperand(I.getOperand(1));
}
if (I.isTailCall()) Out << " /*tail*/ ";
-
- const PointerType *PTy = cast<PointerType>(Callee->getType());
- const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
if (!WroteCallee) {
// If this is an indirect call to a struct return function, we need to cast
++ArgNo;
}
+ const ParamAttrsList *Attrs = FTy->getParamAttrs();
bool PrintedArg = false;
unsigned Idx = 1;
for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
(*AI)->getType() != FTy->getParamType(ArgNo)) {
Out << '(';
printType(Out, FTy->getParamType(ArgNo),
- /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute));
+ /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
Out << ')';
}
writeOperand(*AI);
writeOperand(I.getPointerOperand());
if (I.isVolatile()) Out << ')';
Out << " = ";
- writeOperand(I.getOperand(0));
+ Value *Operand = I.getOperand(0);
+ Constant *BitMask = 0;
+ if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
+ if (!ITy->isPowerOf2ByteWidth())
+ // We have a bit width that doesn't match an even power-of-2 byte
+ // size. Consequently we must & the value with the type's bit mask
+ BitMask = ConstantInt::get(ITy, ITy->getBitMask());
+ if (BitMask)
+ Out << "((";
+ writeOperand(Operand);
+ if (BitMask) {
+ Out << ") & ";
+ printConstant(BitMask);
+ Out << ")";
+ }
}
void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {