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/Transforms/Scalar.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/CodeGen/Passes.h"
30 // TargetMachine for the MSIL
31 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
32 const TargetData DataLayout; // Calculates type size & alignment
34 MSILTarget(const Target &T, const Module &M, const std::string &FS)
35 : TargetMachine(T), DataLayout(&M) {}
37 virtual bool WantsWholeFile() const { return true; }
38 virtual bool addPassesToEmitWholeFile(PassManager &PM,
39 formatted_raw_ostream &Out,
40 CodeGenFileType FileType,
41 CodeGenOpt::Level OptLevel);
43 // This class always works, but shouldn't be the default in most cases.
44 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
46 virtual const TargetData *getTargetData() const { return &DataLayout; }
50 extern Target TheMSILTarget;
51 static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
53 // Force static initialization.
54 extern "C" void LLVMInitializeMSILTarget() { }
56 bool MSILModule::runOnModule(Module &M) {
58 TD = &getAnalysis<TargetData>();
61 TypeSymbolTable& Table = M.getTypeSymbolTable();
62 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
63 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
64 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
67 std::set<const Type *>::iterator T = Types.find(I->second);
76 // Find unnamed types.
77 unsigned RenameCounter = 0;
78 for (std::set<const Type *>::const_iterator I = Types.begin(),
79 E = Types.end(); I!=E; ++I)
80 if (const StructType *STy = dyn_cast<StructType>(*I)) {
81 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
85 // Pointer for FunctionPass.
86 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
90 char MSILModule::ID = 0;
91 char MSILWriter::ID = 0;
93 bool MSILWriter::runOnFunction(Function &F) {
94 if (F.isDeclaration()) return false;
96 // Do not codegen any 'available_externally' functions at all, they have
97 // definitions outside the translation unit.
98 if (F.hasAvailableExternallyLinkage())
101 LInfo = &getAnalysis<LoopInfo>();
107 bool MSILWriter::doInitialization(Module &M) {
109 Mang = new Mangler(M);
110 Out << ".assembly extern mscorlib {}\n";
111 Out << ".assembly MSIL {}\n\n";
112 Out << "// External\n";
114 Out << "// Declarations\n";
115 printDeclarations(M.getTypeSymbolTable());
116 Out << "// Definitions\n";
117 printGlobalVariables();
118 Out << "// Startup code\n";
119 printModuleStartup();
124 bool MSILWriter::doFinalization(Module &M) {
130 void MSILWriter::printModuleStartup() {
132 ".method static public int32 $MSIL_Startup() {\n"
134 "\t.locals (native int i)\n"
135 "\t.locals (native int argc)\n"
136 "\t.locals (native int ptr)\n"
137 "\t.locals (void* argv)\n"
138 "\t.locals (string[] args)\n"
139 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
146 printPtrLoad(TD->getPointerSize());
161 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
162 "StringToHGlobalAnsi(string)\n"
166 printPtrLoad(TD->getPointerSize());
178 "\tcall void $MSIL_Init()\n";
180 // Call user 'main' function.
181 const Function* F = ModulePtr->getFunction("main");
182 if (!F || F->isDeclaration()) {
183 Out << "\tldc.i4.0\n\tret\n}\n";
187 std::string Args("");
188 Function::const_arg_iterator Arg1,Arg2;
190 switch (F->arg_size()) {
195 Arg1 = F->arg_begin();
196 if (Arg1->getType()->isInteger()) {
197 Out << "\tldloc\targc\n";
198 Args = getTypeName(Arg1->getType());
203 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
204 if (Arg1->getType()->isInteger() &&
205 Arg2->getType()->getTypeID() == Type::PointerTyID) {
206 Out << "\tldloc\targc\n\tldloc\targv\n";
207 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
215 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
216 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
217 Out << "\tldc.i4.0\n";
219 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
220 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
222 Out << "\tldc.i4.0\n";
224 Out << "\tconv.i4\n";
229 bool MSILWriter::isZeroValue(const Value* V) {
230 if (const Constant *C = dyn_cast<Constant>(V))
231 return C->isNullValue();
236 std::string MSILWriter::getValueName(const Value* V) {
238 if (const GlobalValue *GV = cast<GlobalValue>(V))
239 Name = Mang->getMangledName(GV);
241 unsigned &No = AnonValueNumbers[V];
242 if (No == 0) No = ++NextAnonValueNumber;
243 Name = "tmp" + utostr(No);
246 // Name into the quotes allow control and space characters.
251 std::string MSILWriter::getLabelName(const std::string& Name) {
252 if (Name.find('.')!=std::string::npos) {
253 std::string Tmp(Name);
254 // Replace unaccepable characters in the label name.
255 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
256 if (*I=='.') *I = '@';
263 std::string MSILWriter::getLabelName(const Value* V) {
265 if (const GlobalValue *GV = cast<GlobalValue>(V))
266 Name = Mang->getMangledName(GV);
268 unsigned &No = AnonValueNumbers[V];
269 if (No == 0) No = ++NextAnonValueNumber;
270 Name = "tmp" + utostr(No);
273 return getLabelName(Name);
277 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
278 switch (CallingConvID) {
280 case CallingConv::Cold:
281 case CallingConv::Fast:
282 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
283 case CallingConv::X86_FastCall:
284 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
285 case CallingConv::X86_StdCall:
286 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
288 cerr << "CallingConvID = " << CallingConvID << '\n';
289 llvm_unreachable("Unsupported calling convention");
291 return ""; // Not reached
295 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
296 std::string Tmp = "";
297 const Type* ElemTy = Ty;
298 assert(Ty->getTypeID()==TyID && "Invalid type passed");
299 // Walk trought array element types.
301 // Multidimensional array.
302 if (ElemTy->getTypeID()==TyID) {
303 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
304 Tmp += utostr(ATy->getNumElements());
305 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
306 Tmp += utostr(VTy->getNumElements());
307 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
309 // Base element type found.
310 if (ElemTy->getTypeID()!=TyID) break;
313 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
317 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
318 unsigned NumBits = 0;
319 switch (Ty->getTypeID()) {
322 case Type::IntegerTyID:
323 NumBits = getBitWidth(Ty);
327 return "unsigned int"+utostr(NumBits)+" ";
328 return "int"+utostr(NumBits)+" ";
329 case Type::FloatTyID:
331 case Type::DoubleTyID:
334 cerr << "Type = " << *Ty << '\n';
335 llvm_unreachable("Invalid primitive type");
337 return ""; // Not reached
341 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
343 if (Ty->isPrimitiveType() || Ty->isInteger())
344 return getPrimitiveTypeName(Ty,isSigned);
345 // FIXME: "OpaqueType" support
346 switch (Ty->getTypeID()) {
347 case Type::PointerTyID:
349 case Type::StructTyID:
351 return ModulePtr->getTypeName(Ty);
352 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
353 case Type::ArrayTyID:
355 return getArrayTypeName(Ty->getTypeID(),Ty);
356 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
357 case Type::VectorTyID:
359 return getArrayTypeName(Ty->getTypeID(),Ty);
360 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
362 cerr << "Type = " << *Ty << '\n';
363 llvm_unreachable("Invalid type in getTypeName()");
365 return ""; // Not reached
369 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
371 if (isa<Argument>(V))
374 else if (const Function* F = dyn_cast<Function>(V))
375 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
377 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
378 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
380 else if (isa<Constant>(V))
381 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
387 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
389 unsigned NumBits = 0;
390 switch (Ty->getTypeID()) {
391 // Integer constant, expanding for stack operations.
392 case Type::IntegerTyID:
393 NumBits = getBitWidth(Ty);
394 // Expand integer value to "int32" or "int64".
395 if (Expand) return (NumBits<=32 ? "i4" : "i8");
396 if (NumBits==1) return "i1";
397 return (isSigned ? "i" : "u")+utostr(NumBits/8);
399 case Type::FloatTyID:
401 case Type::DoubleTyID:
403 case Type::PointerTyID:
404 return "i"+utostr(TD->getTypeAllocSize(Ty));
406 cerr << "TypeID = " << Ty->getTypeID() << '\n';
407 llvm_unreachable("Invalid type in TypeToPostfix()");
409 return ""; // Not reached
413 void MSILWriter::printConvToPtr() {
414 switch (ModulePtr->getPointerSize()) {
415 case Module::Pointer32:
416 printSimpleInstruction("conv.u4");
418 case Module::Pointer64:
419 printSimpleInstruction("conv.u8");
422 llvm_unreachable("Module use not supporting pointer size");
427 void MSILWriter::printPtrLoad(uint64_t N) {
428 switch (ModulePtr->getPointerSize()) {
429 case Module::Pointer32:
430 printSimpleInstruction("ldc.i4",utostr(N).c_str());
431 // FIXME: Need overflow test?
433 cerr << "Value = " << utostr(N) << '\n';
434 llvm_unreachable("32-bit pointer overflowed");
437 case Module::Pointer64:
438 printSimpleInstruction("ldc.i8",utostr(N).c_str());
441 llvm_unreachable("Module use not supporting pointer size");
446 void MSILWriter::printValuePtrLoad(const Value* V) {
452 void MSILWriter::printConstLoad(const Constant* C) {
453 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
455 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
456 if (CInt->isMinValue(true))
457 Out << CInt->getSExtValue();
459 Out << CInt->getZExtValue();
460 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
464 if (FP->getType()->getTypeID()==Type::FloatTyID) {
465 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
468 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
471 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
472 } else if (isa<UndefValue>(C)) {
473 // Undefined constant value = NULL.
476 cerr << "Constant = " << *C << '\n';
477 llvm_unreachable("Invalid constant value");
483 void MSILWriter::printValueLoad(const Value* V) {
484 MSILWriter::ValueType Location = getValueLocation(V);
486 // Global variable or function address.
489 if (const Function* F = dyn_cast<Function>(V)) {
490 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
491 printSimpleInstruction("ldftn",
492 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
495 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
496 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
497 Tmp = "void* "+getValueName(V);
498 printSimpleInstruction("ldsfld",Tmp.c_str());
500 Tmp = getTypeName(ElemTy)+getValueName(V);
501 printSimpleInstruction("ldsflda",Tmp.c_str());
505 // Function argument.
507 printSimpleInstruction("ldarg",getValueName(V).c_str());
509 // Local function variable.
511 printSimpleInstruction("ldloc",getValueName(V).c_str());
515 if (isa<ConstantPointerNull>(V))
518 printConstLoad(cast<Constant>(V));
520 // Constant expression.
522 printConstantExpr(cast<ConstantExpr>(V));
525 cerr << "Value = " << *V << '\n';
526 llvm_unreachable("Invalid value location");
531 void MSILWriter::printValueSave(const Value* V) {
532 switch (getValueLocation(V)) {
534 printSimpleInstruction("starg",getValueName(V).c_str());
537 printSimpleInstruction("stloc",getValueName(V).c_str());
540 cerr << "Value = " << *V << '\n';
541 llvm_unreachable("Invalid value location");
546 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
547 const Value* Right) {
548 printValueLoad(Left);
549 printValueLoad(Right);
550 Out << '\t' << Name << '\n';
554 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
556 Out << '\t' << Inst << '\t' << Operand << '\n';
558 Out << '\t' << Inst << '\n';
562 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
563 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
564 isa<PHINode>(I); ++I) {
565 const PHINode* Phi = cast<PHINode>(I);
566 const Value* Val = Phi->getIncomingValueForBlock(Src);
567 if (isa<UndefValue>(Val)) continue;
574 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
575 const BasicBlock* TrueBB,
576 const BasicBlock* FalseBB) {
577 if (TrueBB==FalseBB) {
578 // "TrueBB" and "FalseBB" destination equals
579 printPHICopy(CurrBB,TrueBB);
580 printSimpleInstruction("pop");
581 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
582 } else if (FalseBB==NULL) {
583 // If "FalseBB" not used the jump have condition
584 printPHICopy(CurrBB,TrueBB);
585 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
586 } else if (TrueBB==NULL) {
587 // If "TrueBB" not used the jump is unconditional
588 printPHICopy(CurrBB,FalseBB);
589 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
591 // Copy PHI instructions for each block
592 std::string TmpLabel;
593 // Print PHI instructions for "TrueBB"
594 if (isa<PHINode>(TrueBB->begin())) {
595 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
596 printSimpleInstruction("brtrue",TmpLabel.c_str());
598 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
600 // Print PHI instructions for "FalseBB"
601 if (isa<PHINode>(FalseBB->begin())) {
602 printPHICopy(CurrBB,FalseBB);
603 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
605 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
607 if (isa<PHINode>(TrueBB->begin())) {
608 // Handle "TrueBB" PHI Copy
609 Out << TmpLabel << ":\n";
610 printPHICopy(CurrBB,TrueBB);
611 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
617 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
618 if (Inst->isUnconditional()) {
619 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
621 printValueLoad(Inst->getCondition());
622 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
623 Inst->getSuccessor(1));
628 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
629 const Value* VFalse) {
630 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
631 printValueLoad(VTrue);
632 printValueLoad(Cond);
633 printSimpleInstruction("brtrue",TmpLabel.c_str());
634 printSimpleInstruction("pop");
635 printValueLoad(VFalse);
636 Out << TmpLabel << ":\n";
640 void MSILWriter::printIndirectLoad(const Value* V) {
641 const Type* Ty = V->getType();
643 if (const PointerType* P = dyn_cast<PointerType>(Ty))
644 Ty = P->getElementType();
645 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
646 printSimpleInstruction(Tmp.c_str());
650 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
653 printIndirectSave(Val->getType());
657 void MSILWriter::printIndirectSave(const Type* Ty) {
658 // Instruction need signed postfix for any type.
659 std::string postfix = getTypePostfix(Ty, false);
660 if (*postfix.begin()=='u') *postfix.begin() = 'i';
661 postfix = "stind."+postfix;
662 printSimpleInstruction(postfix.c_str());
666 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
667 const Type* Ty, const Type* SrcTy) {
672 case Instruction::SExt:
673 // If sign extending int, convert first from unsigned to signed
674 // with the same bit size - because otherwise we will loose the sign.
676 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
677 printSimpleInstruction(Tmp.c_str());
680 case Instruction::SIToFP:
681 case Instruction::FPToSI:
682 Tmp = "conv."+getTypePostfix(Ty,false,true);
683 printSimpleInstruction(Tmp.c_str());
686 case Instruction::FPTrunc:
687 case Instruction::FPExt:
688 case Instruction::UIToFP:
689 case Instruction::Trunc:
690 case Instruction::ZExt:
691 case Instruction::FPToUI:
692 case Instruction::PtrToInt:
693 case Instruction::IntToPtr:
694 Tmp = "conv."+getTypePostfix(Ty,false);
695 printSimpleInstruction(Tmp.c_str());
698 case Instruction::BitCast:
699 // FIXME: meaning that ld*/st* instruction do not change data format.
702 cerr << "Opcode = " << Op << '\n';
703 llvm_unreachable("Invalid conversion instruction");
708 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
709 gep_type_iterator E) {
712 printValuePtrLoad(V);
713 // Calculate element offset.
716 const Value* IndexValue = I.getOperand();
717 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
718 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
719 // Offset is the sum of all previous structure fields.
720 for (uint64_t F = 0; F<FieldIndex; ++F)
721 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
723 printSimpleInstruction("add");
725 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
726 Size = TD->getTypeAllocSize(SeqTy->getElementType());
728 Size = TD->getTypeAllocSize(*I);
730 // Add offset of current element to stack top.
731 if (!isZeroValue(IndexValue)) {
732 // Constant optimization.
733 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
734 if (C->getValue().isNegative()) {
735 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
736 printSimpleInstruction("sub");
739 printPtrLoad(C->getZExtValue()*Size);
742 printValuePtrLoad(IndexValue);
743 printSimpleInstruction("mul");
745 printSimpleInstruction("add");
751 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
752 const Instruction* Inst,
755 if (Ty->isVarArg()) Tmp += "vararg ";
756 // Name and return type.
757 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
758 // Function argument type list.
759 unsigned NumParams = Ty->getNumParams();
760 for (unsigned I = 0; I!=NumParams; ++I) {
761 if (I!=0) Tmp += ",";
762 Tmp += getTypeName(Ty->getParamType(I));
764 // CLR needs to know the exact amount of parameters received by vararg
765 // function, because caller cleans the stack.
766 if (Ty->isVarArg() && Inst) {
767 // Origin to function arguments in "CallInst" or "InvokeInst".
768 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
769 // Print variable argument types.
770 unsigned NumOperands = Inst->getNumOperands()-Org;
771 if (NumParams<NumOperands) {
772 if (NumParams!=0) Tmp += ", ";
774 for (unsigned J = NumParams; J!=NumOperands; ++J) {
775 if (J!=NumParams) Tmp += ", ";
776 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
784 void MSILWriter::printFunctionCall(const Value* FnVal,
785 const Instruction* Inst) {
786 // Get function calling convention.
787 std::string Name = "";
788 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
789 Name = getConvModopt(Call->getCallingConv());
790 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
791 Name = getConvModopt(Invoke->getCallingConv());
793 cerr << "Instruction = " << Inst->getName() << '\n';
794 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
796 if (const Function* F = dyn_cast<Function>(FnVal)) {
798 Name += getValueName(F);
799 printSimpleInstruction("call",
800 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
802 // Indirect function call.
803 const PointerType* PTy = cast<PointerType>(FnVal->getType());
804 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
805 // Load function address.
806 printValueLoad(FnVal);
807 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
812 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
814 switch (Inst->getIntrinsicID()) {
815 case Intrinsic::vastart:
816 Name = getValueName(Inst->getOperand(1));
817 Name.insert(Name.length()-1,"$valist");
818 // Obtain the argument handle.
819 printSimpleInstruction("ldloca",Name.c_str());
820 printSimpleInstruction("arglist");
821 printSimpleInstruction("call",
822 "instance void [mscorlib]System.ArgIterator::.ctor"
823 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
824 // Save as pointer type "void*"
825 printValueLoad(Inst->getOperand(1));
826 printSimpleInstruction("ldloca",Name.c_str());
827 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
829 case Intrinsic::vaend:
830 // Close argument list handle.
831 printIndirectLoad(Inst->getOperand(1));
832 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
834 case Intrinsic::vacopy:
835 // Copy "ArgIterator" valuetype.
836 printIndirectLoad(Inst->getOperand(1));
837 printIndirectLoad(Inst->getOperand(2));
838 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
841 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
842 llvm_unreachable("Invalid intrinsic function");
847 void MSILWriter::printCallInstruction(const Instruction* Inst) {
848 if (isa<IntrinsicInst>(Inst)) {
849 // Handle intrinsic function.
850 printIntrinsicCall(cast<IntrinsicInst>(Inst));
852 // Load arguments to stack and call function.
853 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
854 printValueLoad(Inst->getOperand(I));
855 printFunctionCall(Inst->getOperand(0),Inst);
860 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
861 const Value* Right) {
863 case ICmpInst::ICMP_EQ:
864 printBinaryInstruction("ceq",Left,Right);
866 case ICmpInst::ICMP_NE:
867 // Emulate = not neg (Op1 eq Op2)
868 printBinaryInstruction("ceq",Left,Right);
869 printSimpleInstruction("neg");
870 printSimpleInstruction("not");
872 case ICmpInst::ICMP_ULE:
873 case ICmpInst::ICMP_SLE:
874 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
875 printBinaryInstruction("ceq",Left,Right);
876 if (Predicate==ICmpInst::ICMP_ULE)
877 printBinaryInstruction("clt.un",Left,Right);
879 printBinaryInstruction("clt",Left,Right);
880 printSimpleInstruction("or");
882 case ICmpInst::ICMP_UGE:
883 case ICmpInst::ICMP_SGE:
884 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
885 printBinaryInstruction("ceq",Left,Right);
886 if (Predicate==ICmpInst::ICMP_UGE)
887 printBinaryInstruction("cgt.un",Left,Right);
889 printBinaryInstruction("cgt",Left,Right);
890 printSimpleInstruction("or");
892 case ICmpInst::ICMP_ULT:
893 printBinaryInstruction("clt.un",Left,Right);
895 case ICmpInst::ICMP_SLT:
896 printBinaryInstruction("clt",Left,Right);
898 case ICmpInst::ICMP_UGT:
899 printBinaryInstruction("cgt.un",Left,Right);
901 case ICmpInst::ICMP_SGT:
902 printBinaryInstruction("cgt",Left,Right);
905 cerr << "Predicate = " << Predicate << '\n';
906 llvm_unreachable("Invalid icmp predicate");
911 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
912 const Value* Right) {
913 // FIXME: Correct comparison
914 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
916 case FCmpInst::FCMP_UGT:
917 // X > Y || llvm_fcmp_uno(X, Y)
918 printBinaryInstruction("cgt",Left,Right);
919 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
920 printSimpleInstruction("or");
922 case FCmpInst::FCMP_OGT:
924 printBinaryInstruction("cgt",Left,Right);
926 case FCmpInst::FCMP_UGE:
927 // X >= Y || llvm_fcmp_uno(X, Y)
928 printBinaryInstruction("ceq",Left,Right);
929 printBinaryInstruction("cgt",Left,Right);
930 printSimpleInstruction("or");
931 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
932 printSimpleInstruction("or");
934 case FCmpInst::FCMP_OGE:
936 printBinaryInstruction("ceq",Left,Right);
937 printBinaryInstruction("cgt",Left,Right);
938 printSimpleInstruction("or");
940 case FCmpInst::FCMP_ULT:
941 // X < Y || llvm_fcmp_uno(X, Y)
942 printBinaryInstruction("clt",Left,Right);
943 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
944 printSimpleInstruction("or");
946 case FCmpInst::FCMP_OLT:
948 printBinaryInstruction("clt",Left,Right);
950 case FCmpInst::FCMP_ULE:
951 // X <= Y || llvm_fcmp_uno(X, Y)
952 printBinaryInstruction("ceq",Left,Right);
953 printBinaryInstruction("clt",Left,Right);
954 printSimpleInstruction("or");
955 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
956 printSimpleInstruction("or");
958 case FCmpInst::FCMP_OLE:
960 printBinaryInstruction("ceq",Left,Right);
961 printBinaryInstruction("clt",Left,Right);
962 printSimpleInstruction("or");
964 case FCmpInst::FCMP_UEQ:
965 // X == Y || llvm_fcmp_uno(X, Y)
966 printBinaryInstruction("ceq",Left,Right);
967 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
968 printSimpleInstruction("or");
970 case FCmpInst::FCMP_OEQ:
972 printBinaryInstruction("ceq",Left,Right);
974 case FCmpInst::FCMP_UNE:
976 printBinaryInstruction("ceq",Left,Right);
977 printSimpleInstruction("neg");
978 printSimpleInstruction("not");
980 case FCmpInst::FCMP_ONE:
981 // X != Y && llvm_fcmp_ord(X, Y)
982 printBinaryInstruction("ceq",Left,Right);
983 printSimpleInstruction("not");
985 case FCmpInst::FCMP_ORD:
986 // return X == X && Y == Y
987 printBinaryInstruction("ceq",Left,Left);
988 printBinaryInstruction("ceq",Right,Right);
989 printSimpleInstruction("or");
991 case FCmpInst::FCMP_UNO:
993 printBinaryInstruction("ceq",Left,Left);
994 printSimpleInstruction("not");
995 printBinaryInstruction("ceq",Right,Right);
996 printSimpleInstruction("not");
997 printSimpleInstruction("or");
1000 llvm_unreachable("Illegal FCmp predicate");
1005 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1006 std::string Label = "leave$normal_"+utostr(getUniqID());
1009 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1010 printValueLoad(Inst->getOperand(I));
1011 // Print call instruction
1012 printFunctionCall(Inst->getOperand(0),Inst);
1013 // Save function result and leave "try" block
1014 printValueSave(Inst);
1015 printSimpleInstruction("leave",Label.c_str());
1017 Out << "catch [mscorlib]System.Exception {\n";
1018 // Redirect to unwind block
1019 printSimpleInstruction("pop");
1020 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1021 Out << "}\n" << Label << ":\n";
1022 // Redirect to continue block
1023 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1027 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1028 // FIXME: Emulate with IL "switch" instruction
1029 // Emulate = if () else if () else if () else ...
1030 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1031 printValueLoad(Inst->getCondition());
1032 printValueLoad(Inst->getCaseValue(I));
1033 printSimpleInstruction("ceq");
1034 // Condition jump to successor block
1035 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1037 // Jump to default block
1038 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1042 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1043 printIndirectLoad(Inst->getOperand(0));
1044 printSimpleInstruction("call",
1045 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1046 printSimpleInstruction("refanyval","void*");
1048 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1049 printSimpleInstruction(Name.c_str());
1053 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1054 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1055 // Constant optimization.
1056 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1057 printPtrLoad(CInt->getZExtValue()*Size);
1060 printValueLoad(Inst->getOperand(0));
1061 printSimpleInstruction("mul");
1063 printSimpleInstruction("localloc");
1067 void MSILWriter::printInstruction(const Instruction* Inst) {
1068 const Value *Left = 0, *Right = 0;
1069 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1070 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1071 // Print instruction
1072 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1073 switch (Inst->getOpcode()) {
1075 case Instruction::Ret:
1076 if (Inst->getNumOperands()) {
1077 printValueLoad(Left);
1078 printSimpleInstruction("ret");
1080 printSimpleInstruction("ret");
1082 case Instruction::Br:
1083 printBranchInstruction(cast<BranchInst>(Inst));
1086 case Instruction::Add:
1087 case Instruction::FAdd:
1088 printBinaryInstruction("add",Left,Right);
1090 case Instruction::Sub:
1091 case Instruction::FSub:
1092 printBinaryInstruction("sub",Left,Right);
1094 case Instruction::Mul:
1095 case Instruction::FMul:
1096 printBinaryInstruction("mul",Left,Right);
1098 case Instruction::UDiv:
1099 printBinaryInstruction("div.un",Left,Right);
1101 case Instruction::SDiv:
1102 case Instruction::FDiv:
1103 printBinaryInstruction("div",Left,Right);
1105 case Instruction::URem:
1106 printBinaryInstruction("rem.un",Left,Right);
1108 case Instruction::SRem:
1109 case Instruction::FRem:
1110 printBinaryInstruction("rem",Left,Right);
1113 case Instruction::ICmp:
1114 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1116 case Instruction::FCmp:
1117 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1120 case Instruction::And:
1121 printBinaryInstruction("and",Left,Right);
1123 case Instruction::Or:
1124 printBinaryInstruction("or",Left,Right);
1126 case Instruction::Xor:
1127 printBinaryInstruction("xor",Left,Right);
1129 case Instruction::Shl:
1130 printValueLoad(Left);
1131 printValueLoad(Right);
1132 printSimpleInstruction("conv.i4");
1133 printSimpleInstruction("shl");
1135 case Instruction::LShr:
1136 printValueLoad(Left);
1137 printValueLoad(Right);
1138 printSimpleInstruction("conv.i4");
1139 printSimpleInstruction("shr.un");
1141 case Instruction::AShr:
1142 printValueLoad(Left);
1143 printValueLoad(Right);
1144 printSimpleInstruction("conv.i4");
1145 printSimpleInstruction("shr");
1147 case Instruction::Select:
1148 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1150 case Instruction::Load:
1151 printIndirectLoad(Inst->getOperand(0));
1153 case Instruction::Store:
1154 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1156 case Instruction::SExt:
1157 printCastInstruction(Inst->getOpcode(),Left,
1158 cast<CastInst>(Inst)->getDestTy(),
1159 cast<CastInst>(Inst)->getSrcTy());
1161 case Instruction::Trunc:
1162 case Instruction::ZExt:
1163 case Instruction::FPTrunc:
1164 case Instruction::FPExt:
1165 case Instruction::UIToFP:
1166 case Instruction::SIToFP:
1167 case Instruction::FPToUI:
1168 case Instruction::FPToSI:
1169 case Instruction::PtrToInt:
1170 case Instruction::IntToPtr:
1171 case Instruction::BitCast:
1172 printCastInstruction(Inst->getOpcode(),Left,
1173 cast<CastInst>(Inst)->getDestTy());
1175 case Instruction::GetElementPtr:
1176 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1177 gep_type_end(Inst));
1179 case Instruction::Call:
1180 printCallInstruction(cast<CallInst>(Inst));
1182 case Instruction::Invoke:
1183 printInvokeInstruction(cast<InvokeInst>(Inst));
1185 case Instruction::Unwind:
1186 printSimpleInstruction("newobj",
1187 "instance void [mscorlib]System.Exception::.ctor()");
1188 printSimpleInstruction("throw");
1190 case Instruction::Switch:
1191 printSwitchInstruction(cast<SwitchInst>(Inst));
1193 case Instruction::Alloca:
1194 printAllocaInstruction(cast<AllocaInst>(Inst));
1196 case Instruction::Malloc:
1197 llvm_unreachable("LowerAllocationsPass used");
1199 case Instruction::Free:
1200 llvm_unreachable("LowerAllocationsPass used");
1202 case Instruction::Unreachable:
1203 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1204 printSimpleInstruction("newobj",
1205 "instance void [mscorlib]System.Exception::.ctor(string)");
1206 printSimpleInstruction("throw");
1208 case Instruction::VAArg:
1209 printVAArgInstruction(cast<VAArgInst>(Inst));
1212 cerr << "Instruction = " << Inst->getName() << '\n';
1213 llvm_unreachable("Unsupported instruction");
1218 void MSILWriter::printLoop(const Loop* L) {
1219 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1220 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1221 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1222 BasicBlock* BB = blocks[I];
1223 Loop* BBLoop = LInfo->getLoopFor(BB);
1225 printBasicBlock(BB);
1226 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1229 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1233 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1234 Out << getLabelName(BB) << ":\n";
1235 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1236 const Instruction* Inst = I;
1237 // Comment llvm original instruction
1238 // Out << "\n//" << *Inst << "\n";
1239 // Do not handle PHI instruction in current block
1240 if (Inst->getOpcode()==Instruction::PHI) continue;
1241 // Print instruction
1242 printInstruction(Inst);
1244 if (Inst->getType()!=Type::VoidTy) {
1245 // Do not save value after invoke, it done in "try" block
1246 if (Inst->getOpcode()==Instruction::Invoke) continue;
1247 printValueSave(Inst);
1253 void MSILWriter::printLocalVariables(const Function& F) {
1255 const Type* Ty = NULL;
1256 std::set<const Value*> Printed;
1257 const Value* VaList = NULL;
1258 unsigned StackDepth = 8;
1259 // Find local variables
1260 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1261 if (I->getOpcode()==Instruction::Call ||
1262 I->getOpcode()==Instruction::Invoke) {
1263 // Test stack depth.
1264 if (StackDepth<I->getNumOperands())
1265 StackDepth = I->getNumOperands();
1267 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1268 if (AI && !isa<GlobalVariable>(AI)) {
1269 // Local variable allocation.
1270 Ty = PointerType::getUnqual(AI->getAllocatedType());
1271 Name = getValueName(AI);
1272 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1273 } else if (I->getType()!=Type::VoidTy) {
1274 // Operation result.
1276 Name = getValueName(&*I);
1277 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1279 // Test on 'va_list' variable
1280 bool isVaList = false;
1281 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1282 // "va_list" as "va_arg" instruction operand.
1284 VaList = VaInst->getOperand(0);
1285 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1286 // "va_list" as intrinsic function operand.
1287 switch (Inst->getIntrinsicID()) {
1288 case Intrinsic::vastart:
1289 case Intrinsic::vaend:
1290 case Intrinsic::vacopy:
1292 VaList = Inst->getOperand(1);
1298 // Print "va_list" variable.
1299 if (isVaList && Printed.insert(VaList).second) {
1300 Name = getValueName(VaList);
1301 Name.insert(Name.length()-1,"$valist");
1302 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1306 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1310 void MSILWriter::printFunctionBody(const Function& F) {
1312 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1313 if (Loop *L = LInfo->getLoopFor(I)) {
1314 if (L->getHeader()==I && L->getParentLoop()==0)
1323 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1324 const Value *left = 0, *right = 0;
1325 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1326 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1327 // Print instruction
1328 switch (CE->getOpcode()) {
1329 case Instruction::Trunc:
1330 case Instruction::ZExt:
1331 case Instruction::SExt:
1332 case Instruction::FPTrunc:
1333 case Instruction::FPExt:
1334 case Instruction::UIToFP:
1335 case Instruction::SIToFP:
1336 case Instruction::FPToUI:
1337 case Instruction::FPToSI:
1338 case Instruction::PtrToInt:
1339 case Instruction::IntToPtr:
1340 case Instruction::BitCast:
1341 printCastInstruction(CE->getOpcode(),left,CE->getType());
1343 case Instruction::GetElementPtr:
1344 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1346 case Instruction::ICmp:
1347 printICmpInstruction(CE->getPredicate(),left,right);
1349 case Instruction::FCmp:
1350 printFCmpInstruction(CE->getPredicate(),left,right);
1352 case Instruction::Select:
1353 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1355 case Instruction::Add:
1356 case Instruction::FAdd:
1357 printBinaryInstruction("add",left,right);
1359 case Instruction::Sub:
1360 case Instruction::FSub:
1361 printBinaryInstruction("sub",left,right);
1363 case Instruction::Mul:
1364 case Instruction::FMul:
1365 printBinaryInstruction("mul",left,right);
1367 case Instruction::UDiv:
1368 printBinaryInstruction("div.un",left,right);
1370 case Instruction::SDiv:
1371 case Instruction::FDiv:
1372 printBinaryInstruction("div",left,right);
1374 case Instruction::URem:
1375 printBinaryInstruction("rem.un",left,right);
1377 case Instruction::SRem:
1378 case Instruction::FRem:
1379 printBinaryInstruction("rem",left,right);
1381 case Instruction::And:
1382 printBinaryInstruction("and",left,right);
1384 case Instruction::Or:
1385 printBinaryInstruction("or",left,right);
1387 case Instruction::Xor:
1388 printBinaryInstruction("xor",left,right);
1390 case Instruction::Shl:
1391 printBinaryInstruction("shl",left,right);
1393 case Instruction::LShr:
1394 printBinaryInstruction("shr.un",left,right);
1396 case Instruction::AShr:
1397 printBinaryInstruction("shr",left,right);
1400 cerr << "Expression = " << *CE << "\n";
1401 llvm_unreachable("Invalid constant expression");
1406 void MSILWriter::printStaticInitializerList() {
1407 // List of global variables with uninitialized fields.
1408 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1409 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1411 const std::vector<StaticInitializer>& InitList = VarI->second;
1412 if (InitList.empty()) continue;
1413 // For each uninitialized field.
1414 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1415 E = InitList.end(); I!=E; ++I) {
1416 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1417 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1418 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1419 // Load variable address
1420 printValueLoad(VarI->first);
1423 printPtrLoad(I->offset);
1424 printSimpleInstruction("add");
1427 printConstantExpr(CE);
1428 // Save result at offset
1429 std::string postfix = getTypePostfix(CE->getType(),true);
1430 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1431 postfix = "stind."+postfix;
1432 printSimpleInstruction(postfix.c_str());
1434 cerr << "Constant = " << *I->constant << '\n';
1435 llvm_unreachable("Invalid static initializer");
1442 void MSILWriter::printFunction(const Function& F) {
1443 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1444 Out << "\n.method static ";
1445 Out << (F.hasLocalLinkage() ? "private " : "public ");
1446 if (F.isVarArg()) Out << "vararg ";
1447 Out << getTypeName(F.getReturnType(),isSigned) <<
1448 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1451 unsigned ArgIdx = 1;
1452 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1454 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1455 if (I!=F.arg_begin()) Out << ", ";
1456 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1458 Out << ") cil managed\n";
1461 printLocalVariables(F);
1462 printFunctionBody(F);
1467 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1469 std::set<const Type*> Printed;
1470 for (std::set<const Type*>::const_iterator
1471 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1472 const Type* Ty = *UI;
1473 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1474 Name = getTypeName(Ty, false, true);
1475 // Type with no need to declare.
1477 // Print not duplicated type
1478 if (Printed.insert(Ty).second) {
1479 Out << ".class value explicit ansi sealed '" << Name << "'";
1480 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1487 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1488 unsigned int N = Ty->getPrimitiveSizeInBits();
1489 assert(N!=0 && "Invalid type in getBitWidth()");
1498 cerr << "Bits = " << N << '\n';
1499 llvm_unreachable("Unsupported integer width");
1501 return 0; // Not reached
1505 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1506 uint64_t TySize = 0;
1507 const Type* Ty = C->getType();
1508 // Print zero initialized constant.
1509 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1510 TySize = TD->getTypeAllocSize(C->getType());
1512 Out << "int8 (0) [" << TySize << "]";
1515 // Print constant initializer
1516 switch (Ty->getTypeID()) {
1517 case Type::IntegerTyID: {
1518 TySize = TD->getTypeAllocSize(Ty);
1519 const ConstantInt* Int = cast<ConstantInt>(C);
1520 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1523 case Type::FloatTyID:
1524 case Type::DoubleTyID: {
1525 TySize = TD->getTypeAllocSize(Ty);
1526 const ConstantFP* FP = cast<ConstantFP>(C);
1527 if (Ty->getTypeID() == Type::FloatTyID)
1529 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1532 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1535 case Type::ArrayTyID:
1536 case Type::VectorTyID:
1537 case Type::StructTyID:
1538 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1539 if (I!=0) Out << ",\n";
1540 printStaticConstant(C->getOperand(I),Offset);
1543 case Type::PointerTyID:
1544 TySize = TD->getTypeAllocSize(C->getType());
1545 // Initialize with global variable address
1546 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1547 std::string name = getValueName(G);
1548 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1550 // Dynamic initialization
1551 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1552 InitListPtr->push_back(StaticInitializer(C,Offset));
1553 // Null pointer initialization
1554 if (TySize==4) Out << "int32 (0)";
1555 else if (TySize==8) Out << "int64 (0)";
1556 else llvm_unreachable("Invalid pointer size");
1560 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1561 llvm_unreachable("Invalid type in printStaticConstant()");
1568 void MSILWriter::printStaticInitializer(const Constant* C,
1569 const std::string& Name) {
1570 switch (C->getType()->getTypeID()) {
1571 case Type::IntegerTyID:
1572 case Type::FloatTyID:
1573 case Type::DoubleTyID:
1574 Out << getPrimitiveTypeName(C->getType(), false);
1576 case Type::ArrayTyID:
1577 case Type::VectorTyID:
1578 case Type::StructTyID:
1579 case Type::PointerTyID:
1580 Out << getTypeName(C->getType());
1583 cerr << "Type = " << *C << "\n";
1584 llvm_unreachable("Invalid constant type");
1586 // Print initializer
1587 std::string label = Name;
1588 label.insert(label.length()-1,"$data");
1589 Out << Name << " at " << label << '\n';
1590 Out << ".data " << label << " = {\n";
1591 uint64_t offset = 0;
1592 printStaticConstant(C,offset);
1597 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1598 const Constant* C = G->getInitializer();
1599 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1602 InitListPtr = &StaticInitList[G];
1603 printStaticInitializer(C,getValueName(G));
1607 void MSILWriter::printGlobalVariables() {
1608 if (ModulePtr->global_empty()) return;
1609 Module::global_iterator I,E;
1610 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1611 // Variable definition
1612 Out << ".field static " << (I->isDeclaration() ? "public " :
1614 if (I->isDeclaration()) {
1615 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1617 printVariableDefinition(&*I);
1622 const char* MSILWriter::getLibraryName(const Function* F) {
1623 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1627 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1628 return getLibraryForSymbol(Mang->getMangledName(GV).c_str(), false, 0);
1632 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1633 unsigned CallingConv) {
1634 // TODO: Read *.def file with function and libraries definitions.
1635 return "MSVCRT.DLL";
1639 void MSILWriter::printExternals() {
1640 Module::const_iterator I,E;
1642 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1644 if (I->isIntrinsic()) continue;
1645 if (I->isDeclaration()) {
1646 const Function* F = I;
1647 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1649 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1650 Out << ".method static hidebysig pinvokeimpl(\""
1651 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1654 // External variables and static initialization.
1656 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1657 " native int LoadLibrary(string) preservesig {}\n"
1658 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1659 " native int GetProcAddress(native int, string) preservesig {}\n";
1661 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1664 "\tcall\tnative int LoadLibrary(string)\n"
1666 "\tcall\tnative int GetProcAddress(native int,string)\n"
1669 "\tldstr\t\"Can no import variable\"\n"
1670 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1675 ".method static private void $MSIL_Init() managed cil\n{\n";
1676 printStaticInitializerList();
1677 // Foreach global variable.
1678 for (Module::global_iterator I = ModulePtr->global_begin(),
1679 E = ModulePtr->global_end(); I!=E; ++I) {
1680 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1681 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1682 std::string Label = "not_null$_"+utostr(getUniqID());
1683 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1684 printSimpleInstruction("ldsflda",Tmp.c_str());
1685 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1686 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
1687 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1688 printIndirectSave(I->getType());
1690 printSimpleInstruction("ret");
1695 //===----------------------------------------------------------------------===//
1696 // External Interface declaration
1697 //===----------------------------------------------------------------------===//
1699 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1700 formatted_raw_ostream &o,
1701 CodeGenFileType FileType,
1702 CodeGenOpt::Level OptLevel)
1704 if (FileType != TargetMachine::AssemblyFile) return true;
1705 MSILWriter* Writer = new MSILWriter(o);
1706 PM.add(createGCLoweringPass());
1707 PM.add(createLowerAllocationsPass(true));
1708 // FIXME: Handle switch trougth native IL instruction "switch"
1709 PM.add(createLowerSwitchPass());
1710 PM.add(createCFGSimplificationPass());
1711 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1713 PM.add(createGCInfoDeleter());