1 //===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
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 MSIL code.
12 //===----------------------------------------------------------------------===//
14 #include "MSILWriter.h"
15 #include "llvm/CallingConv.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/TypeSymbolTable.h"
20 #include "llvm/Analysis/ConstantsScanner.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/Passes.h"
32 // TargetMachine for the MSIL
33 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
34 const TargetData DataLayout; // Calculates type size & alignment
36 MSILTarget(const Target &T, const Module &M, const std::string &FS)
37 : TargetMachine(T), DataLayout(&M) {}
39 virtual bool WantsWholeFile() const { return true; }
40 virtual bool addPassesToEmitWholeFile(PassManager &PM,
41 formatted_raw_ostream &Out,
42 CodeGenFileType FileType,
43 CodeGenOpt::Level OptLevel);
45 // This class always works, but shouldn't be the default in most cases.
46 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
48 virtual const TargetData *getTargetData() const { return &DataLayout; }
52 extern "C" void LLVMInitializeMSILTarget() {
53 // Register the target.
54 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
57 bool MSILModule::runOnModule(Module &M) {
59 TD = &getAnalysis<TargetData>();
62 TypeSymbolTable& Table = M.getTypeSymbolTable();
63 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
64 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
65 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
68 std::set<const Type *>::iterator T = Types.find(I->second);
77 // Find unnamed types.
78 unsigned RenameCounter = 0;
79 for (std::set<const Type *>::const_iterator I = Types.begin(),
80 E = Types.end(); I!=E; ++I)
81 if (const StructType *STy = dyn_cast<StructType>(*I)) {
82 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
86 // Pointer for FunctionPass.
87 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
91 char MSILModule::ID = 0;
92 char MSILWriter::ID = 0;
94 bool MSILWriter::runOnFunction(Function &F) {
95 if (F.isDeclaration()) return false;
97 // Do not codegen any 'available_externally' functions at all, they have
98 // definitions outside the translation unit.
99 if (F.hasAvailableExternallyLinkage())
102 LInfo = &getAnalysis<LoopInfo>();
108 bool MSILWriter::doInitialization(Module &M) {
110 Mang = new Mangler(M);
111 Out << ".assembly extern mscorlib {}\n";
112 Out << ".assembly MSIL {}\n\n";
113 Out << "// External\n";
115 Out << "// Declarations\n";
116 printDeclarations(M.getTypeSymbolTable());
117 Out << "// Definitions\n";
118 printGlobalVariables();
119 Out << "// Startup code\n";
120 printModuleStartup();
125 bool MSILWriter::doFinalization(Module &M) {
131 void MSILWriter::printModuleStartup() {
133 ".method static public int32 $MSIL_Startup() {\n"
135 "\t.locals (native int i)\n"
136 "\t.locals (native int argc)\n"
137 "\t.locals (native int ptr)\n"
138 "\t.locals (void* argv)\n"
139 "\t.locals (string[] args)\n"
140 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
147 printPtrLoad(TD->getPointerSize());
162 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
163 "StringToHGlobalAnsi(string)\n"
167 printPtrLoad(TD->getPointerSize());
179 "\tcall void $MSIL_Init()\n";
181 // Call user 'main' function.
182 const Function* F = ModulePtr->getFunction("main");
183 if (!F || F->isDeclaration()) {
184 Out << "\tldc.i4.0\n\tret\n}\n";
188 std::string Args("");
189 Function::const_arg_iterator Arg1,Arg2;
191 switch (F->arg_size()) {
196 Arg1 = F->arg_begin();
197 if (Arg1->getType()->isInteger()) {
198 Out << "\tldloc\targc\n";
199 Args = getTypeName(Arg1->getType());
204 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
205 if (Arg1->getType()->isInteger() &&
206 Arg2->getType()->getTypeID() == Type::PointerTyID) {
207 Out << "\tldloc\targc\n\tldloc\targv\n";
208 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
216 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
217 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
218 Out << "\tldc.i4.0\n";
220 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
221 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
223 Out << "\tldc.i4.0\n";
225 Out << "\tconv.i4\n";
230 bool MSILWriter::isZeroValue(const Value* V) {
231 if (const Constant *C = dyn_cast<Constant>(V))
232 return C->isNullValue();
237 std::string MSILWriter::getValueName(const Value* V) {
239 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
240 Name = Mang->getMangledName(GV);
242 unsigned &No = AnonValueNumbers[V];
243 if (No == 0) No = ++NextAnonValueNumber;
244 Name = "tmp" + utostr(No);
247 // Name into the quotes allow control and space characters.
252 std::string MSILWriter::getLabelName(const std::string& Name) {
253 if (Name.find('.')!=std::string::npos) {
254 std::string Tmp(Name);
255 // Replace unaccepable characters in the label name.
256 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
257 if (*I=='.') *I = '@';
264 std::string MSILWriter::getLabelName(const Value* V) {
266 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
267 Name = Mang->getMangledName(GV);
269 unsigned &No = AnonValueNumbers[V];
270 if (No == 0) No = ++NextAnonValueNumber;
271 Name = "tmp" + utostr(No);
274 return getLabelName(Name);
278 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
279 switch (CallingConvID) {
281 case CallingConv::Cold:
282 case CallingConv::Fast:
283 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
284 case CallingConv::X86_FastCall:
285 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
286 case CallingConv::X86_StdCall:
287 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
289 cerr << "CallingConvID = " << CallingConvID << '\n';
290 llvm_unreachable("Unsupported calling convention");
292 return ""; // Not reached
296 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
297 std::string Tmp = "";
298 const Type* ElemTy = Ty;
299 assert(Ty->getTypeID()==TyID && "Invalid type passed");
300 // Walk trought array element types.
302 // Multidimensional array.
303 if (ElemTy->getTypeID()==TyID) {
304 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
305 Tmp += utostr(ATy->getNumElements());
306 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
307 Tmp += utostr(VTy->getNumElements());
308 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
310 // Base element type found.
311 if (ElemTy->getTypeID()!=TyID) break;
314 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
318 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
319 unsigned NumBits = 0;
320 switch (Ty->getTypeID()) {
323 case Type::IntegerTyID:
324 NumBits = getBitWidth(Ty);
328 return "unsigned int"+utostr(NumBits)+" ";
329 return "int"+utostr(NumBits)+" ";
330 case Type::FloatTyID:
332 case Type::DoubleTyID:
335 cerr << "Type = " << *Ty << '\n';
336 llvm_unreachable("Invalid primitive type");
338 return ""; // Not reached
342 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
344 if (Ty->isPrimitiveType() || Ty->isInteger())
345 return getPrimitiveTypeName(Ty,isSigned);
346 // FIXME: "OpaqueType" support
347 switch (Ty->getTypeID()) {
348 case Type::PointerTyID:
350 case Type::StructTyID:
352 return ModulePtr->getTypeName(Ty);
353 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
354 case Type::ArrayTyID:
356 return getArrayTypeName(Ty->getTypeID(),Ty);
357 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
358 case Type::VectorTyID:
360 return getArrayTypeName(Ty->getTypeID(),Ty);
361 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
363 cerr << "Type = " << *Ty << '\n';
364 llvm_unreachable("Invalid type in getTypeName()");
366 return ""; // Not reached
370 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
372 if (isa<Argument>(V))
375 else if (const Function* F = dyn_cast<Function>(V))
376 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
378 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
379 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
381 else if (isa<Constant>(V))
382 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
388 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
390 unsigned NumBits = 0;
391 switch (Ty->getTypeID()) {
392 // Integer constant, expanding for stack operations.
393 case Type::IntegerTyID:
394 NumBits = getBitWidth(Ty);
395 // Expand integer value to "int32" or "int64".
396 if (Expand) return (NumBits<=32 ? "i4" : "i8");
397 if (NumBits==1) return "i1";
398 return (isSigned ? "i" : "u")+utostr(NumBits/8);
400 case Type::FloatTyID:
402 case Type::DoubleTyID:
404 case Type::PointerTyID:
405 return "i"+utostr(TD->getTypeAllocSize(Ty));
407 cerr << "TypeID = " << Ty->getTypeID() << '\n';
408 llvm_unreachable("Invalid type in TypeToPostfix()");
410 return ""; // Not reached
414 void MSILWriter::printConvToPtr() {
415 switch (ModulePtr->getPointerSize()) {
416 case Module::Pointer32:
417 printSimpleInstruction("conv.u4");
419 case Module::Pointer64:
420 printSimpleInstruction("conv.u8");
423 llvm_unreachable("Module use not supporting pointer size");
428 void MSILWriter::printPtrLoad(uint64_t N) {
429 switch (ModulePtr->getPointerSize()) {
430 case Module::Pointer32:
431 printSimpleInstruction("ldc.i4",utostr(N).c_str());
432 // FIXME: Need overflow test?
434 cerr << "Value = " << utostr(N) << '\n';
435 llvm_unreachable("32-bit pointer overflowed");
438 case Module::Pointer64:
439 printSimpleInstruction("ldc.i8",utostr(N).c_str());
442 llvm_unreachable("Module use not supporting pointer size");
447 void MSILWriter::printValuePtrLoad(const Value* V) {
453 void MSILWriter::printConstLoad(const Constant* C) {
454 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
456 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
457 if (CInt->isMinValue(true))
458 Out << CInt->getSExtValue();
460 Out << CInt->getZExtValue();
461 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
465 if (FP->getType()->getTypeID()==Type::FloatTyID) {
466 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
469 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
472 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
473 } else if (isa<UndefValue>(C)) {
474 // Undefined constant value = NULL.
477 cerr << "Constant = " << *C << '\n';
478 llvm_unreachable("Invalid constant value");
484 void MSILWriter::printValueLoad(const Value* V) {
485 MSILWriter::ValueType Location = getValueLocation(V);
487 // Global variable or function address.
490 if (const Function* F = dyn_cast<Function>(V)) {
491 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
492 printSimpleInstruction("ldftn",
493 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
496 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
497 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
498 Tmp = "void* "+getValueName(V);
499 printSimpleInstruction("ldsfld",Tmp.c_str());
501 Tmp = getTypeName(ElemTy)+getValueName(V);
502 printSimpleInstruction("ldsflda",Tmp.c_str());
506 // Function argument.
508 printSimpleInstruction("ldarg",getValueName(V).c_str());
510 // Local function variable.
512 printSimpleInstruction("ldloc",getValueName(V).c_str());
516 if (isa<ConstantPointerNull>(V))
519 printConstLoad(cast<Constant>(V));
521 // Constant expression.
523 printConstantExpr(cast<ConstantExpr>(V));
526 cerr << "Value = " << *V << '\n';
527 llvm_unreachable("Invalid value location");
532 void MSILWriter::printValueSave(const Value* V) {
533 switch (getValueLocation(V)) {
535 printSimpleInstruction("starg",getValueName(V).c_str());
538 printSimpleInstruction("stloc",getValueName(V).c_str());
541 cerr << "Value = " << *V << '\n';
542 llvm_unreachable("Invalid value location");
547 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
548 const Value* Right) {
549 printValueLoad(Left);
550 printValueLoad(Right);
551 Out << '\t' << Name << '\n';
555 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
557 Out << '\t' << Inst << '\t' << Operand << '\n';
559 Out << '\t' << Inst << '\n';
563 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
564 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
565 isa<PHINode>(I); ++I) {
566 const PHINode* Phi = cast<PHINode>(I);
567 const Value* Val = Phi->getIncomingValueForBlock(Src);
568 if (isa<UndefValue>(Val)) continue;
575 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
576 const BasicBlock* TrueBB,
577 const BasicBlock* FalseBB) {
578 if (TrueBB==FalseBB) {
579 // "TrueBB" and "FalseBB" destination equals
580 printPHICopy(CurrBB,TrueBB);
581 printSimpleInstruction("pop");
582 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
583 } else if (FalseBB==NULL) {
584 // If "FalseBB" not used the jump have condition
585 printPHICopy(CurrBB,TrueBB);
586 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
587 } else if (TrueBB==NULL) {
588 // If "TrueBB" not used the jump is unconditional
589 printPHICopy(CurrBB,FalseBB);
590 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
592 // Copy PHI instructions for each block
593 std::string TmpLabel;
594 // Print PHI instructions for "TrueBB"
595 if (isa<PHINode>(TrueBB->begin())) {
596 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
597 printSimpleInstruction("brtrue",TmpLabel.c_str());
599 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
601 // Print PHI instructions for "FalseBB"
602 if (isa<PHINode>(FalseBB->begin())) {
603 printPHICopy(CurrBB,FalseBB);
604 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
606 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
608 if (isa<PHINode>(TrueBB->begin())) {
609 // Handle "TrueBB" PHI Copy
610 Out << TmpLabel << ":\n";
611 printPHICopy(CurrBB,TrueBB);
612 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
618 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
619 if (Inst->isUnconditional()) {
620 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
622 printValueLoad(Inst->getCondition());
623 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
624 Inst->getSuccessor(1));
629 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
630 const Value* VFalse) {
631 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
632 printValueLoad(VTrue);
633 printValueLoad(Cond);
634 printSimpleInstruction("brtrue",TmpLabel.c_str());
635 printSimpleInstruction("pop");
636 printValueLoad(VFalse);
637 Out << TmpLabel << ":\n";
641 void MSILWriter::printIndirectLoad(const Value* V) {
642 const Type* Ty = V->getType();
644 if (const PointerType* P = dyn_cast<PointerType>(Ty))
645 Ty = P->getElementType();
646 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
647 printSimpleInstruction(Tmp.c_str());
651 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
654 printIndirectSave(Val->getType());
658 void MSILWriter::printIndirectSave(const Type* Ty) {
659 // Instruction need signed postfix for any type.
660 std::string postfix = getTypePostfix(Ty, false);
661 if (*postfix.begin()=='u') *postfix.begin() = 'i';
662 postfix = "stind."+postfix;
663 printSimpleInstruction(postfix.c_str());
667 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
668 const Type* Ty, const Type* SrcTy) {
673 case Instruction::SExt:
674 // If sign extending int, convert first from unsigned to signed
675 // with the same bit size - because otherwise we will loose the sign.
677 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
678 printSimpleInstruction(Tmp.c_str());
681 case Instruction::SIToFP:
682 case Instruction::FPToSI:
683 Tmp = "conv."+getTypePostfix(Ty,false,true);
684 printSimpleInstruction(Tmp.c_str());
687 case Instruction::FPTrunc:
688 case Instruction::FPExt:
689 case Instruction::UIToFP:
690 case Instruction::Trunc:
691 case Instruction::ZExt:
692 case Instruction::FPToUI:
693 case Instruction::PtrToInt:
694 case Instruction::IntToPtr:
695 Tmp = "conv."+getTypePostfix(Ty,false);
696 printSimpleInstruction(Tmp.c_str());
699 case Instruction::BitCast:
700 // FIXME: meaning that ld*/st* instruction do not change data format.
703 cerr << "Opcode = " << Op << '\n';
704 llvm_unreachable("Invalid conversion instruction");
709 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
710 gep_type_iterator E) {
713 printValuePtrLoad(V);
714 // Calculate element offset.
717 const Value* IndexValue = I.getOperand();
718 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
719 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
720 // Offset is the sum of all previous structure fields.
721 for (uint64_t F = 0; F<FieldIndex; ++F)
722 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
724 printSimpleInstruction("add");
726 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
727 Size = TD->getTypeAllocSize(SeqTy->getElementType());
729 Size = TD->getTypeAllocSize(*I);
731 // Add offset of current element to stack top.
732 if (!isZeroValue(IndexValue)) {
733 // Constant optimization.
734 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
735 if (C->getValue().isNegative()) {
736 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
737 printSimpleInstruction("sub");
740 printPtrLoad(C->getZExtValue()*Size);
743 printValuePtrLoad(IndexValue);
744 printSimpleInstruction("mul");
746 printSimpleInstruction("add");
752 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
753 const Instruction* Inst,
756 if (Ty->isVarArg()) Tmp += "vararg ";
757 // Name and return type.
758 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
759 // Function argument type list.
760 unsigned NumParams = Ty->getNumParams();
761 for (unsigned I = 0; I!=NumParams; ++I) {
762 if (I!=0) Tmp += ",";
763 Tmp += getTypeName(Ty->getParamType(I));
765 // CLR needs to know the exact amount of parameters received by vararg
766 // function, because caller cleans the stack.
767 if (Ty->isVarArg() && Inst) {
768 // Origin to function arguments in "CallInst" or "InvokeInst".
769 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
770 // Print variable argument types.
771 unsigned NumOperands = Inst->getNumOperands()-Org;
772 if (NumParams<NumOperands) {
773 if (NumParams!=0) Tmp += ", ";
775 for (unsigned J = NumParams; J!=NumOperands; ++J) {
776 if (J!=NumParams) Tmp += ", ";
777 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
785 void MSILWriter::printFunctionCall(const Value* FnVal,
786 const Instruction* Inst) {
787 // Get function calling convention.
788 std::string Name = "";
789 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
790 Name = getConvModopt(Call->getCallingConv());
791 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
792 Name = getConvModopt(Invoke->getCallingConv());
794 errs() << "Instruction = " << Inst->getName() << '\n';
795 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
797 if (const Function* F = dyn_cast<Function>(FnVal)) {
799 Name += getValueName(F);
800 printSimpleInstruction("call",
801 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
803 // Indirect function call.
804 const PointerType* PTy = cast<PointerType>(FnVal->getType());
805 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
806 // Load function address.
807 printValueLoad(FnVal);
808 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
813 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
815 switch (Inst->getIntrinsicID()) {
816 case Intrinsic::vastart:
817 Name = getValueName(Inst->getOperand(1));
818 Name.insert(Name.length()-1,"$valist");
819 // Obtain the argument handle.
820 printSimpleInstruction("ldloca",Name.c_str());
821 printSimpleInstruction("arglist");
822 printSimpleInstruction("call",
823 "instance void [mscorlib]System.ArgIterator::.ctor"
824 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
825 // Save as pointer type "void*"
826 printValueLoad(Inst->getOperand(1));
827 printSimpleInstruction("ldloca",Name.c_str());
828 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
830 case Intrinsic::vaend:
831 // Close argument list handle.
832 printIndirectLoad(Inst->getOperand(1));
833 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
835 case Intrinsic::vacopy:
836 // Copy "ArgIterator" valuetype.
837 printIndirectLoad(Inst->getOperand(1));
838 printIndirectLoad(Inst->getOperand(2));
839 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
842 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
843 llvm_unreachable("Invalid intrinsic function");
848 void MSILWriter::printCallInstruction(const Instruction* Inst) {
849 if (isa<IntrinsicInst>(Inst)) {
850 // Handle intrinsic function.
851 printIntrinsicCall(cast<IntrinsicInst>(Inst));
853 // Load arguments to stack and call function.
854 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
855 printValueLoad(Inst->getOperand(I));
856 printFunctionCall(Inst->getOperand(0),Inst);
861 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
862 const Value* Right) {
864 case ICmpInst::ICMP_EQ:
865 printBinaryInstruction("ceq",Left,Right);
867 case ICmpInst::ICMP_NE:
868 // Emulate = not neg (Op1 eq Op2)
869 printBinaryInstruction("ceq",Left,Right);
870 printSimpleInstruction("neg");
871 printSimpleInstruction("not");
873 case ICmpInst::ICMP_ULE:
874 case ICmpInst::ICMP_SLE:
875 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
876 printBinaryInstruction("ceq",Left,Right);
877 if (Predicate==ICmpInst::ICMP_ULE)
878 printBinaryInstruction("clt.un",Left,Right);
880 printBinaryInstruction("clt",Left,Right);
881 printSimpleInstruction("or");
883 case ICmpInst::ICMP_UGE:
884 case ICmpInst::ICMP_SGE:
885 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
886 printBinaryInstruction("ceq",Left,Right);
887 if (Predicate==ICmpInst::ICMP_UGE)
888 printBinaryInstruction("cgt.un",Left,Right);
890 printBinaryInstruction("cgt",Left,Right);
891 printSimpleInstruction("or");
893 case ICmpInst::ICMP_ULT:
894 printBinaryInstruction("clt.un",Left,Right);
896 case ICmpInst::ICMP_SLT:
897 printBinaryInstruction("clt",Left,Right);
899 case ICmpInst::ICMP_UGT:
900 printBinaryInstruction("cgt.un",Left,Right);
902 case ICmpInst::ICMP_SGT:
903 printBinaryInstruction("cgt",Left,Right);
906 errs() << "Predicate = " << Predicate << '\n';
907 llvm_unreachable("Invalid icmp predicate");
912 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
913 const Value* Right) {
914 // FIXME: Correct comparison
915 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
917 case FCmpInst::FCMP_UGT:
918 // X > Y || llvm_fcmp_uno(X, Y)
919 printBinaryInstruction("cgt",Left,Right);
920 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
921 printSimpleInstruction("or");
923 case FCmpInst::FCMP_OGT:
925 printBinaryInstruction("cgt",Left,Right);
927 case FCmpInst::FCMP_UGE:
928 // X >= Y || llvm_fcmp_uno(X, Y)
929 printBinaryInstruction("ceq",Left,Right);
930 printBinaryInstruction("cgt",Left,Right);
931 printSimpleInstruction("or");
932 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
933 printSimpleInstruction("or");
935 case FCmpInst::FCMP_OGE:
937 printBinaryInstruction("ceq",Left,Right);
938 printBinaryInstruction("cgt",Left,Right);
939 printSimpleInstruction("or");
941 case FCmpInst::FCMP_ULT:
942 // X < Y || llvm_fcmp_uno(X, Y)
943 printBinaryInstruction("clt",Left,Right);
944 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
945 printSimpleInstruction("or");
947 case FCmpInst::FCMP_OLT:
949 printBinaryInstruction("clt",Left,Right);
951 case FCmpInst::FCMP_ULE:
952 // X <= Y || llvm_fcmp_uno(X, Y)
953 printBinaryInstruction("ceq",Left,Right);
954 printBinaryInstruction("clt",Left,Right);
955 printSimpleInstruction("or");
956 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
957 printSimpleInstruction("or");
959 case FCmpInst::FCMP_OLE:
961 printBinaryInstruction("ceq",Left,Right);
962 printBinaryInstruction("clt",Left,Right);
963 printSimpleInstruction("or");
965 case FCmpInst::FCMP_UEQ:
966 // X == Y || llvm_fcmp_uno(X, Y)
967 printBinaryInstruction("ceq",Left,Right);
968 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
969 printSimpleInstruction("or");
971 case FCmpInst::FCMP_OEQ:
973 printBinaryInstruction("ceq",Left,Right);
975 case FCmpInst::FCMP_UNE:
977 printBinaryInstruction("ceq",Left,Right);
978 printSimpleInstruction("neg");
979 printSimpleInstruction("not");
981 case FCmpInst::FCMP_ONE:
982 // X != Y && llvm_fcmp_ord(X, Y)
983 printBinaryInstruction("ceq",Left,Right);
984 printSimpleInstruction("not");
986 case FCmpInst::FCMP_ORD:
987 // return X == X && Y == Y
988 printBinaryInstruction("ceq",Left,Left);
989 printBinaryInstruction("ceq",Right,Right);
990 printSimpleInstruction("or");
992 case FCmpInst::FCMP_UNO:
994 printBinaryInstruction("ceq",Left,Left);
995 printSimpleInstruction("not");
996 printBinaryInstruction("ceq",Right,Right);
997 printSimpleInstruction("not");
998 printSimpleInstruction("or");
1001 llvm_unreachable("Illegal FCmp predicate");
1006 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1007 std::string Label = "leave$normal_"+utostr(getUniqID());
1010 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1011 printValueLoad(Inst->getOperand(I));
1012 // Print call instruction
1013 printFunctionCall(Inst->getOperand(0),Inst);
1014 // Save function result and leave "try" block
1015 printValueSave(Inst);
1016 printSimpleInstruction("leave",Label.c_str());
1018 Out << "catch [mscorlib]System.Exception {\n";
1019 // Redirect to unwind block
1020 printSimpleInstruction("pop");
1021 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1022 Out << "}\n" << Label << ":\n";
1023 // Redirect to continue block
1024 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1028 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1029 // FIXME: Emulate with IL "switch" instruction
1030 // Emulate = if () else if () else if () else ...
1031 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1032 printValueLoad(Inst->getCondition());
1033 printValueLoad(Inst->getCaseValue(I));
1034 printSimpleInstruction("ceq");
1035 // Condition jump to successor block
1036 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1038 // Jump to default block
1039 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1043 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1044 printIndirectLoad(Inst->getOperand(0));
1045 printSimpleInstruction("call",
1046 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1047 printSimpleInstruction("refanyval","void*");
1049 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1050 printSimpleInstruction(Name.c_str());
1054 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1055 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1056 // Constant optimization.
1057 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1058 printPtrLoad(CInt->getZExtValue()*Size);
1061 printValueLoad(Inst->getOperand(0));
1062 printSimpleInstruction("mul");
1064 printSimpleInstruction("localloc");
1068 void MSILWriter::printInstruction(const Instruction* Inst) {
1069 const Value *Left = 0, *Right = 0;
1070 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1071 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1072 // Print instruction
1073 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1074 switch (Inst->getOpcode()) {
1076 case Instruction::Ret:
1077 if (Inst->getNumOperands()) {
1078 printValueLoad(Left);
1079 printSimpleInstruction("ret");
1081 printSimpleInstruction("ret");
1083 case Instruction::Br:
1084 printBranchInstruction(cast<BranchInst>(Inst));
1087 case Instruction::Add:
1088 case Instruction::FAdd:
1089 printBinaryInstruction("add",Left,Right);
1091 case Instruction::Sub:
1092 case Instruction::FSub:
1093 printBinaryInstruction("sub",Left,Right);
1095 case Instruction::Mul:
1096 case Instruction::FMul:
1097 printBinaryInstruction("mul",Left,Right);
1099 case Instruction::UDiv:
1100 printBinaryInstruction("div.un",Left,Right);
1102 case Instruction::SDiv:
1103 case Instruction::FDiv:
1104 printBinaryInstruction("div",Left,Right);
1106 case Instruction::URem:
1107 printBinaryInstruction("rem.un",Left,Right);
1109 case Instruction::SRem:
1110 case Instruction::FRem:
1111 printBinaryInstruction("rem",Left,Right);
1114 case Instruction::ICmp:
1115 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1117 case Instruction::FCmp:
1118 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1121 case Instruction::And:
1122 printBinaryInstruction("and",Left,Right);
1124 case Instruction::Or:
1125 printBinaryInstruction("or",Left,Right);
1127 case Instruction::Xor:
1128 printBinaryInstruction("xor",Left,Right);
1130 case Instruction::Shl:
1131 printValueLoad(Left);
1132 printValueLoad(Right);
1133 printSimpleInstruction("conv.i4");
1134 printSimpleInstruction("shl");
1136 case Instruction::LShr:
1137 printValueLoad(Left);
1138 printValueLoad(Right);
1139 printSimpleInstruction("conv.i4");
1140 printSimpleInstruction("shr.un");
1142 case Instruction::AShr:
1143 printValueLoad(Left);
1144 printValueLoad(Right);
1145 printSimpleInstruction("conv.i4");
1146 printSimpleInstruction("shr");
1148 case Instruction::Select:
1149 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1151 case Instruction::Load:
1152 printIndirectLoad(Inst->getOperand(0));
1154 case Instruction::Store:
1155 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1157 case Instruction::SExt:
1158 printCastInstruction(Inst->getOpcode(),Left,
1159 cast<CastInst>(Inst)->getDestTy(),
1160 cast<CastInst>(Inst)->getSrcTy());
1162 case Instruction::Trunc:
1163 case Instruction::ZExt:
1164 case Instruction::FPTrunc:
1165 case Instruction::FPExt:
1166 case Instruction::UIToFP:
1167 case Instruction::SIToFP:
1168 case Instruction::FPToUI:
1169 case Instruction::FPToSI:
1170 case Instruction::PtrToInt:
1171 case Instruction::IntToPtr:
1172 case Instruction::BitCast:
1173 printCastInstruction(Inst->getOpcode(),Left,
1174 cast<CastInst>(Inst)->getDestTy());
1176 case Instruction::GetElementPtr:
1177 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1178 gep_type_end(Inst));
1180 case Instruction::Call:
1181 printCallInstruction(cast<CallInst>(Inst));
1183 case Instruction::Invoke:
1184 printInvokeInstruction(cast<InvokeInst>(Inst));
1186 case Instruction::Unwind:
1187 printSimpleInstruction("newobj",
1188 "instance void [mscorlib]System.Exception::.ctor()");
1189 printSimpleInstruction("throw");
1191 case Instruction::Switch:
1192 printSwitchInstruction(cast<SwitchInst>(Inst));
1194 case Instruction::Alloca:
1195 printAllocaInstruction(cast<AllocaInst>(Inst));
1197 case Instruction::Malloc:
1198 llvm_unreachable("LowerAllocationsPass used");
1200 case Instruction::Free:
1201 llvm_unreachable("LowerAllocationsPass used");
1203 case Instruction::Unreachable:
1204 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1205 printSimpleInstruction("newobj",
1206 "instance void [mscorlib]System.Exception::.ctor(string)");
1207 printSimpleInstruction("throw");
1209 case Instruction::VAArg:
1210 printVAArgInstruction(cast<VAArgInst>(Inst));
1213 errs() << "Instruction = " << Inst->getName() << '\n';
1214 llvm_unreachable("Unsupported instruction");
1219 void MSILWriter::printLoop(const Loop* L) {
1220 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1221 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1222 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1223 BasicBlock* BB = blocks[I];
1224 Loop* BBLoop = LInfo->getLoopFor(BB);
1226 printBasicBlock(BB);
1227 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1230 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1234 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1235 Out << getLabelName(BB) << ":\n";
1236 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1237 const Instruction* Inst = I;
1238 // Comment llvm original instruction
1239 // Out << "\n//" << *Inst << "\n";
1240 // Do not handle PHI instruction in current block
1241 if (Inst->getOpcode()==Instruction::PHI) continue;
1242 // Print instruction
1243 printInstruction(Inst);
1245 if (Inst->getType()!=Type::VoidTy) {
1246 // Do not save value after invoke, it done in "try" block
1247 if (Inst->getOpcode()==Instruction::Invoke) continue;
1248 printValueSave(Inst);
1254 void MSILWriter::printLocalVariables(const Function& F) {
1256 const Type* Ty = NULL;
1257 std::set<const Value*> Printed;
1258 const Value* VaList = NULL;
1259 unsigned StackDepth = 8;
1260 // Find local variables
1261 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1262 if (I->getOpcode()==Instruction::Call ||
1263 I->getOpcode()==Instruction::Invoke) {
1264 // Test stack depth.
1265 if (StackDepth<I->getNumOperands())
1266 StackDepth = I->getNumOperands();
1268 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1269 if (AI && !isa<GlobalVariable>(AI)) {
1270 // Local variable allocation.
1271 Ty = PointerType::getUnqual(AI->getAllocatedType());
1272 Name = getValueName(AI);
1273 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1274 } else if (I->getType()!=Type::VoidTy) {
1275 // Operation result.
1277 Name = getValueName(&*I);
1278 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1280 // Test on 'va_list' variable
1281 bool isVaList = false;
1282 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1283 // "va_list" as "va_arg" instruction operand.
1285 VaList = VaInst->getOperand(0);
1286 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1287 // "va_list" as intrinsic function operand.
1288 switch (Inst->getIntrinsicID()) {
1289 case Intrinsic::vastart:
1290 case Intrinsic::vaend:
1291 case Intrinsic::vacopy:
1293 VaList = Inst->getOperand(1);
1299 // Print "va_list" variable.
1300 if (isVaList && Printed.insert(VaList).second) {
1301 Name = getValueName(VaList);
1302 Name.insert(Name.length()-1,"$valist");
1303 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1307 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1311 void MSILWriter::printFunctionBody(const Function& F) {
1313 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1314 if (Loop *L = LInfo->getLoopFor(I)) {
1315 if (L->getHeader()==I && L->getParentLoop()==0)
1324 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1325 const Value *left = 0, *right = 0;
1326 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1327 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1328 // Print instruction
1329 switch (CE->getOpcode()) {
1330 case Instruction::Trunc:
1331 case Instruction::ZExt:
1332 case Instruction::SExt:
1333 case Instruction::FPTrunc:
1334 case Instruction::FPExt:
1335 case Instruction::UIToFP:
1336 case Instruction::SIToFP:
1337 case Instruction::FPToUI:
1338 case Instruction::FPToSI:
1339 case Instruction::PtrToInt:
1340 case Instruction::IntToPtr:
1341 case Instruction::BitCast:
1342 printCastInstruction(CE->getOpcode(),left,CE->getType());
1344 case Instruction::GetElementPtr:
1345 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1347 case Instruction::ICmp:
1348 printICmpInstruction(CE->getPredicate(),left,right);
1350 case Instruction::FCmp:
1351 printFCmpInstruction(CE->getPredicate(),left,right);
1353 case Instruction::Select:
1354 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1356 case Instruction::Add:
1357 case Instruction::FAdd:
1358 printBinaryInstruction("add",left,right);
1360 case Instruction::Sub:
1361 case Instruction::FSub:
1362 printBinaryInstruction("sub",left,right);
1364 case Instruction::Mul:
1365 case Instruction::FMul:
1366 printBinaryInstruction("mul",left,right);
1368 case Instruction::UDiv:
1369 printBinaryInstruction("div.un",left,right);
1371 case Instruction::SDiv:
1372 case Instruction::FDiv:
1373 printBinaryInstruction("div",left,right);
1375 case Instruction::URem:
1376 printBinaryInstruction("rem.un",left,right);
1378 case Instruction::SRem:
1379 case Instruction::FRem:
1380 printBinaryInstruction("rem",left,right);
1382 case Instruction::And:
1383 printBinaryInstruction("and",left,right);
1385 case Instruction::Or:
1386 printBinaryInstruction("or",left,right);
1388 case Instruction::Xor:
1389 printBinaryInstruction("xor",left,right);
1391 case Instruction::Shl:
1392 printBinaryInstruction("shl",left,right);
1394 case Instruction::LShr:
1395 printBinaryInstruction("shr.un",left,right);
1397 case Instruction::AShr:
1398 printBinaryInstruction("shr",left,right);
1401 errs() << "Expression = " << *CE << "\n";
1402 llvm_unreachable("Invalid constant expression");
1407 void MSILWriter::printStaticInitializerList() {
1408 // List of global variables with uninitialized fields.
1409 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1410 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1412 const std::vector<StaticInitializer>& InitList = VarI->second;
1413 if (InitList.empty()) continue;
1414 // For each uninitialized field.
1415 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1416 E = InitList.end(); I!=E; ++I) {
1417 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1418 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1419 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1420 // Load variable address
1421 printValueLoad(VarI->first);
1424 printPtrLoad(I->offset);
1425 printSimpleInstruction("add");
1428 printConstantExpr(CE);
1429 // Save result at offset
1430 std::string postfix = getTypePostfix(CE->getType(),true);
1431 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1432 postfix = "stind."+postfix;
1433 printSimpleInstruction(postfix.c_str());
1435 errs() << "Constant = " << *I->constant << '\n';
1436 llvm_unreachable("Invalid static initializer");
1443 void MSILWriter::printFunction(const Function& F) {
1444 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1445 Out << "\n.method static ";
1446 Out << (F.hasLocalLinkage() ? "private " : "public ");
1447 if (F.isVarArg()) Out << "vararg ";
1448 Out << getTypeName(F.getReturnType(),isSigned) <<
1449 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1452 unsigned ArgIdx = 1;
1453 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1455 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1456 if (I!=F.arg_begin()) Out << ", ";
1457 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1459 Out << ") cil managed\n";
1462 printLocalVariables(F);
1463 printFunctionBody(F);
1468 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1470 std::set<const Type*> Printed;
1471 for (std::set<const Type*>::const_iterator
1472 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1473 const Type* Ty = *UI;
1474 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1475 Name = getTypeName(Ty, false, true);
1476 // Type with no need to declare.
1478 // Print not duplicated type
1479 if (Printed.insert(Ty).second) {
1480 Out << ".class value explicit ansi sealed '" << Name << "'";
1481 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1488 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1489 unsigned int N = Ty->getPrimitiveSizeInBits();
1490 assert(N!=0 && "Invalid type in getBitWidth()");
1499 errs() << "Bits = " << N << '\n';
1500 llvm_unreachable("Unsupported integer width");
1502 return 0; // Not reached
1506 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1507 uint64_t TySize = 0;
1508 const Type* Ty = C->getType();
1509 // Print zero initialized constant.
1510 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1511 TySize = TD->getTypeAllocSize(C->getType());
1513 Out << "int8 (0) [" << TySize << "]";
1516 // Print constant initializer
1517 switch (Ty->getTypeID()) {
1518 case Type::IntegerTyID: {
1519 TySize = TD->getTypeAllocSize(Ty);
1520 const ConstantInt* Int = cast<ConstantInt>(C);
1521 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1524 case Type::FloatTyID:
1525 case Type::DoubleTyID: {
1526 TySize = TD->getTypeAllocSize(Ty);
1527 const ConstantFP* FP = cast<ConstantFP>(C);
1528 if (Ty->getTypeID() == Type::FloatTyID)
1530 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1533 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1536 case Type::ArrayTyID:
1537 case Type::VectorTyID:
1538 case Type::StructTyID:
1539 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1540 if (I!=0) Out << ",\n";
1541 printStaticConstant(C->getOperand(I),Offset);
1544 case Type::PointerTyID:
1545 TySize = TD->getTypeAllocSize(C->getType());
1546 // Initialize with global variable address
1547 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1548 std::string name = getValueName(G);
1549 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1551 // Dynamic initialization
1552 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1553 InitListPtr->push_back(StaticInitializer(C,Offset));
1554 // Null pointer initialization
1555 if (TySize==4) Out << "int32 (0)";
1556 else if (TySize==8) Out << "int64 (0)";
1557 else llvm_unreachable("Invalid pointer size");
1561 errs() << "TypeID = " << Ty->getTypeID() << '\n';
1562 llvm_unreachable("Invalid type in printStaticConstant()");
1569 void MSILWriter::printStaticInitializer(const Constant* C,
1570 const std::string& Name) {
1571 switch (C->getType()->getTypeID()) {
1572 case Type::IntegerTyID:
1573 case Type::FloatTyID:
1574 case Type::DoubleTyID:
1575 Out << getPrimitiveTypeName(C->getType(), false);
1577 case Type::ArrayTyID:
1578 case Type::VectorTyID:
1579 case Type::StructTyID:
1580 case Type::PointerTyID:
1581 Out << getTypeName(C->getType());
1584 errs() << "Type = " << *C << "\n";
1585 llvm_unreachable("Invalid constant type");
1587 // Print initializer
1588 std::string label = Name;
1589 label.insert(label.length()-1,"$data");
1590 Out << Name << " at " << label << '\n';
1591 Out << ".data " << label << " = {\n";
1592 uint64_t offset = 0;
1593 printStaticConstant(C,offset);
1598 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1599 const Constant* C = G->getInitializer();
1600 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1603 InitListPtr = &StaticInitList[G];
1604 printStaticInitializer(C,getValueName(G));
1608 void MSILWriter::printGlobalVariables() {
1609 if (ModulePtr->global_empty()) return;
1610 Module::global_iterator I,E;
1611 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1612 // Variable definition
1613 Out << ".field static " << (I->isDeclaration() ? "public " :
1615 if (I->isDeclaration()) {
1616 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1618 printVariableDefinition(&*I);
1623 const char* MSILWriter::getLibraryName(const Function* F) {
1624 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
1628 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1629 return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
1633 const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1635 unsigned CallingConv) {
1636 // TODO: Read *.def file with function and libraries definitions.
1637 return "MSVCRT.DLL";
1641 void MSILWriter::printExternals() {
1642 Module::const_iterator I,E;
1644 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1646 if (I->isIntrinsic()) continue;
1647 if (I->isDeclaration()) {
1648 const Function* F = I;
1649 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1651 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1652 Out << ".method static hidebysig pinvokeimpl(\""
1653 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1656 // External variables and static initialization.
1658 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1659 " native int LoadLibrary(string) preservesig {}\n"
1660 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1661 " native int GetProcAddress(native int, string) preservesig {}\n";
1663 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1666 "\tcall\tnative int LoadLibrary(string)\n"
1668 "\tcall\tnative int GetProcAddress(native int,string)\n"
1671 "\tldstr\t\"Can no import variable\"\n"
1672 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1677 ".method static private void $MSIL_Init() managed cil\n{\n";
1678 printStaticInitializerList();
1679 // Foreach global variable.
1680 for (Module::global_iterator I = ModulePtr->global_begin(),
1681 E = ModulePtr->global_end(); I!=E; ++I) {
1682 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1683 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1684 std::string Label = "not_null$_"+utostr(getUniqID());
1685 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1686 printSimpleInstruction("ldsflda",Tmp.c_str());
1687 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1688 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
1689 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1690 printIndirectSave(I->getType());
1692 printSimpleInstruction("ret");
1697 //===----------------------------------------------------------------------===//
1698 // External Interface declaration
1699 //===----------------------------------------------------------------------===//
1701 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1702 formatted_raw_ostream &o,
1703 CodeGenFileType FileType,
1704 CodeGenOpt::Level OptLevel)
1706 if (FileType != TargetMachine::AssemblyFile) return true;
1707 MSILWriter* Writer = new MSILWriter(o);
1708 PM.add(createGCLoweringPass());
1709 PM.add(createLowerAllocationsPass(true));
1710 // FIXME: Handle switch trougth native IL instruction "switch"
1711 PM.add(createLowerSwitchPass());
1712 PM.add(createCFGSimplificationPass());
1713 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1715 PM.add(createGCInfoDeleter());