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/InstVisitor.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/Passes.h"
29 // TargetMachine for the MSIL
30 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
31 const TargetData DataLayout; // Calculates type size & alignment
33 MSILTarget(const Module &M, const std::string &FS)
36 virtual bool WantsWholeFile() const { return true; }
37 virtual bool addPassesToEmitWholeFile(PassManager &PM, raw_ostream &Out,
38 CodeGenFileType FileType,
39 CodeGenOpt::Level OptLevel);
41 // This class always works, but shouldn't be the default in most cases.
42 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
44 virtual const TargetData *getTargetData() const { return &DataLayout; }
48 /// MSILTargetMachineModule - Note that this is used on hosts that
49 /// cannot link in a library unless there are references into the
50 /// library. In particular, it seems that it is not possible to get
51 /// things to work on Win32 without this. Though it is unused, do not
53 extern "C" int MSILTargetMachineModule;
54 int MSILTargetMachineModule = 0;
56 static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
58 // Force static initialization when called from llvm/InitializeAllTargets.h
60 void InitializeMSILTarget() { }
63 bool MSILModule::runOnModule(Module &M) {
65 TD = &getAnalysis<TargetData>();
68 TypeSymbolTable& Table = M.getTypeSymbolTable();
69 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
70 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
71 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
74 std::set<const Type *>::iterator T = Types.find(I->second);
83 // Find unnamed types.
84 unsigned RenameCounter = 0;
85 for (std::set<const Type *>::const_iterator I = Types.begin(),
86 E = Types.end(); I!=E; ++I)
87 if (const StructType *STy = dyn_cast<StructType>(*I)) {
88 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
92 // Pointer for FunctionPass.
93 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
97 char MSILModule::ID = 0;
98 char MSILWriter::ID = 0;
100 bool MSILWriter::runOnFunction(Function &F) {
101 if (F.isDeclaration()) return false;
103 // Do not codegen any 'available_externally' functions at all, they have
104 // definitions outside the translation unit.
105 if (F.hasAvailableExternallyLinkage())
108 LInfo = &getAnalysis<LoopInfo>();
114 bool MSILWriter::doInitialization(Module &M) {
116 Mang = new Mangler(M);
117 Out << ".assembly extern mscorlib {}\n";
118 Out << ".assembly MSIL {}\n\n";
119 Out << "// External\n";
121 Out << "// Declarations\n";
122 printDeclarations(M.getTypeSymbolTable());
123 Out << "// Definitions\n";
124 printGlobalVariables();
125 Out << "// Startup code\n";
126 printModuleStartup();
131 bool MSILWriter::doFinalization(Module &M) {
137 void MSILWriter::printModuleStartup() {
139 ".method static public int32 $MSIL_Startup() {\n"
141 "\t.locals (native int i)\n"
142 "\t.locals (native int argc)\n"
143 "\t.locals (native int ptr)\n"
144 "\t.locals (void* argv)\n"
145 "\t.locals (string[] args)\n"
146 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
153 printPtrLoad(TD->getPointerSize());
168 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
169 "StringToHGlobalAnsi(string)\n"
173 printPtrLoad(TD->getPointerSize());
185 "\tcall void $MSIL_Init()\n";
187 // Call user 'main' function.
188 const Function* F = ModulePtr->getFunction("main");
189 if (!F || F->isDeclaration()) {
190 Out << "\tldc.i4.0\n\tret\n}\n";
194 std::string Args("");
195 Function::const_arg_iterator Arg1,Arg2;
197 switch (F->arg_size()) {
202 Arg1 = F->arg_begin();
203 if (Arg1->getType()->isInteger()) {
204 Out << "\tldloc\targc\n";
205 Args = getTypeName(Arg1->getType());
210 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
211 if (Arg1->getType()->isInteger() &&
212 Arg2->getType()->getTypeID() == Type::PointerTyID) {
213 Out << "\tldloc\targc\n\tldloc\targv\n";
214 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
222 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
223 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
224 Out << "\tldc.i4.0\n";
226 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
227 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
229 Out << "\tldc.i4.0\n";
231 Out << "\tconv.i4\n";
236 bool MSILWriter::isZeroValue(const Value* V) {
237 if (const Constant *C = dyn_cast<Constant>(V))
238 return C->isNullValue();
243 std::string MSILWriter::getValueName(const Value* V) {
244 // Name into the quotes allow control and space characters.
245 return "'"+Mang->getValueName(V)+"'";
249 std::string MSILWriter::getLabelName(const std::string& Name) {
250 if (Name.find('.')!=std::string::npos) {
251 std::string Tmp(Name);
252 // Replace unaccepable characters in the label name.
253 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
254 if (*I=='.') *I = '@';
261 std::string MSILWriter::getLabelName(const Value* V) {
262 return getLabelName(Mang->getValueName(V));
266 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
267 switch (CallingConvID) {
269 case CallingConv::Cold:
270 case CallingConv::Fast:
271 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
272 case CallingConv::X86_FastCall:
273 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
274 case CallingConv::X86_StdCall:
275 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
277 cerr << "CallingConvID = " << CallingConvID << '\n';
278 assert(0 && "Unsupported calling convention");
280 return ""; // Not reached
284 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
285 std::string Tmp = "";
286 const Type* ElemTy = Ty;
287 assert(Ty->getTypeID()==TyID && "Invalid type passed");
288 // Walk trought array element types.
290 // Multidimensional array.
291 if (ElemTy->getTypeID()==TyID) {
292 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
293 Tmp += utostr(ATy->getNumElements());
294 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
295 Tmp += utostr(VTy->getNumElements());
296 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
298 // Base element type found.
299 if (ElemTy->getTypeID()!=TyID) break;
302 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
306 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
307 unsigned NumBits = 0;
308 switch (Ty->getTypeID()) {
311 case Type::IntegerTyID:
312 NumBits = getBitWidth(Ty);
316 return "unsigned int"+utostr(NumBits)+" ";
317 return "int"+utostr(NumBits)+" ";
318 case Type::FloatTyID:
320 case Type::DoubleTyID:
323 cerr << "Type = " << *Ty << '\n';
324 assert(0 && "Invalid primitive type");
326 return ""; // Not reached
330 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
332 if (Ty->isPrimitiveType() || Ty->isInteger())
333 return getPrimitiveTypeName(Ty,isSigned);
334 // FIXME: "OpaqueType" support
335 switch (Ty->getTypeID()) {
336 case Type::PointerTyID:
338 case Type::StructTyID:
340 return ModulePtr->getTypeName(Ty);
341 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
342 case Type::ArrayTyID:
344 return getArrayTypeName(Ty->getTypeID(),Ty);
345 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
346 case Type::VectorTyID:
348 return getArrayTypeName(Ty->getTypeID(),Ty);
349 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
351 cerr << "Type = " << *Ty << '\n';
352 assert(0 && "Invalid type in getTypeName()");
354 return ""; // Not reached
358 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
360 if (isa<Argument>(V))
363 else if (const Function* F = dyn_cast<Function>(V))
364 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
366 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
367 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
369 else if (isa<Constant>(V))
370 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
376 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
378 unsigned NumBits = 0;
379 switch (Ty->getTypeID()) {
380 // Integer constant, expanding for stack operations.
381 case Type::IntegerTyID:
382 NumBits = getBitWidth(Ty);
383 // Expand integer value to "int32" or "int64".
384 if (Expand) return (NumBits<=32 ? "i4" : "i8");
385 if (NumBits==1) return "i1";
386 return (isSigned ? "i" : "u")+utostr(NumBits/8);
388 case Type::FloatTyID:
390 case Type::DoubleTyID:
392 case Type::PointerTyID:
393 return "i"+utostr(TD->getTypeAllocSize(Ty));
395 cerr << "TypeID = " << Ty->getTypeID() << '\n';
396 assert(0 && "Invalid type in TypeToPostfix()");
398 return ""; // Not reached
402 void MSILWriter::printConvToPtr() {
403 switch (ModulePtr->getPointerSize()) {
404 case Module::Pointer32:
405 printSimpleInstruction("conv.u4");
407 case Module::Pointer64:
408 printSimpleInstruction("conv.u8");
411 assert(0 && "Module use not supporting pointer size");
416 void MSILWriter::printPtrLoad(uint64_t N) {
417 switch (ModulePtr->getPointerSize()) {
418 case Module::Pointer32:
419 printSimpleInstruction("ldc.i4",utostr(N).c_str());
420 // FIXME: Need overflow test?
422 cerr << "Value = " << utostr(N) << '\n';
423 assert(0 && "32-bit pointer overflowed");
426 case Module::Pointer64:
427 printSimpleInstruction("ldc.i8",utostr(N).c_str());
430 assert(0 && "Module use not supporting pointer size");
435 void MSILWriter::printValuePtrLoad(const Value* V) {
441 void MSILWriter::printConstLoad(const Constant* C) {
442 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
444 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
445 if (CInt->isMinValue(true))
446 Out << CInt->getSExtValue();
448 Out << CInt->getZExtValue();
449 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
453 if (FP->getType()->getTypeID()==Type::FloatTyID) {
454 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
457 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
460 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
461 } else if (isa<UndefValue>(C)) {
462 // Undefined constant value = NULL.
465 cerr << "Constant = " << *C << '\n';
466 assert(0 && "Invalid constant value");
472 void MSILWriter::printValueLoad(const Value* V) {
473 MSILWriter::ValueType Location = getValueLocation(V);
475 // Global variable or function address.
478 if (const Function* F = dyn_cast<Function>(V)) {
479 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
480 printSimpleInstruction("ldftn",
481 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
484 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
485 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
486 Tmp = "void* "+getValueName(V);
487 printSimpleInstruction("ldsfld",Tmp.c_str());
489 Tmp = getTypeName(ElemTy)+getValueName(V);
490 printSimpleInstruction("ldsflda",Tmp.c_str());
494 // Function argument.
496 printSimpleInstruction("ldarg",getValueName(V).c_str());
498 // Local function variable.
500 printSimpleInstruction("ldloc",getValueName(V).c_str());
504 if (isa<ConstantPointerNull>(V))
507 printConstLoad(cast<Constant>(V));
509 // Constant expression.
511 printConstantExpr(cast<ConstantExpr>(V));
514 cerr << "Value = " << *V << '\n';
515 assert(0 && "Invalid value location");
520 void MSILWriter::printValueSave(const Value* V) {
521 switch (getValueLocation(V)) {
523 printSimpleInstruction("starg",getValueName(V).c_str());
526 printSimpleInstruction("stloc",getValueName(V).c_str());
529 cerr << "Value = " << *V << '\n';
530 assert(0 && "Invalid value location");
535 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
536 const Value* Right) {
537 printValueLoad(Left);
538 printValueLoad(Right);
539 Out << '\t' << Name << '\n';
543 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
545 Out << '\t' << Inst << '\t' << Operand << '\n';
547 Out << '\t' << Inst << '\n';
551 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
552 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
553 isa<PHINode>(I); ++I) {
554 const PHINode* Phi = cast<PHINode>(I);
555 const Value* Val = Phi->getIncomingValueForBlock(Src);
556 if (isa<UndefValue>(Val)) continue;
563 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
564 const BasicBlock* TrueBB,
565 const BasicBlock* FalseBB) {
566 if (TrueBB==FalseBB) {
567 // "TrueBB" and "FalseBB" destination equals
568 printPHICopy(CurrBB,TrueBB);
569 printSimpleInstruction("pop");
570 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
571 } else if (FalseBB==NULL) {
572 // If "FalseBB" not used the jump have condition
573 printPHICopy(CurrBB,TrueBB);
574 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
575 } else if (TrueBB==NULL) {
576 // If "TrueBB" not used the jump is unconditional
577 printPHICopy(CurrBB,FalseBB);
578 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
580 // Copy PHI instructions for each block
581 std::string TmpLabel;
582 // Print PHI instructions for "TrueBB"
583 if (isa<PHINode>(TrueBB->begin())) {
584 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
585 printSimpleInstruction("brtrue",TmpLabel.c_str());
587 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
589 // Print PHI instructions for "FalseBB"
590 if (isa<PHINode>(FalseBB->begin())) {
591 printPHICopy(CurrBB,FalseBB);
592 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
594 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
596 if (isa<PHINode>(TrueBB->begin())) {
597 // Handle "TrueBB" PHI Copy
598 Out << TmpLabel << ":\n";
599 printPHICopy(CurrBB,TrueBB);
600 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
606 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
607 if (Inst->isUnconditional()) {
608 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
610 printValueLoad(Inst->getCondition());
611 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
612 Inst->getSuccessor(1));
617 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
618 const Value* VFalse) {
619 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
620 printValueLoad(VTrue);
621 printValueLoad(Cond);
622 printSimpleInstruction("brtrue",TmpLabel.c_str());
623 printSimpleInstruction("pop");
624 printValueLoad(VFalse);
625 Out << TmpLabel << ":\n";
629 void MSILWriter::printIndirectLoad(const Value* V) {
630 const Type* Ty = V->getType();
632 if (const PointerType* P = dyn_cast<PointerType>(Ty))
633 Ty = P->getElementType();
634 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
635 printSimpleInstruction(Tmp.c_str());
639 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
642 printIndirectSave(Val->getType());
646 void MSILWriter::printIndirectSave(const Type* Ty) {
647 // Instruction need signed postfix for any type.
648 std::string postfix = getTypePostfix(Ty, false);
649 if (*postfix.begin()=='u') *postfix.begin() = 'i';
650 postfix = "stind."+postfix;
651 printSimpleInstruction(postfix.c_str());
655 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
661 case Instruction::SExt:
662 case Instruction::SIToFP:
663 case Instruction::FPToSI:
664 Tmp = "conv."+getTypePostfix(Ty,false,true);
665 printSimpleInstruction(Tmp.c_str());
668 case Instruction::FPTrunc:
669 case Instruction::FPExt:
670 case Instruction::UIToFP:
671 case Instruction::Trunc:
672 case Instruction::ZExt:
673 case Instruction::FPToUI:
674 case Instruction::PtrToInt:
675 case Instruction::IntToPtr:
676 Tmp = "conv."+getTypePostfix(Ty,false);
677 printSimpleInstruction(Tmp.c_str());
680 case Instruction::BitCast:
681 // FIXME: meaning that ld*/st* instruction do not change data format.
684 cerr << "Opcode = " << Op << '\n';
685 assert(0 && "Invalid conversion instruction");
690 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
691 gep_type_iterator E) {
694 printValuePtrLoad(V);
695 // Calculate element offset.
698 const Value* IndexValue = I.getOperand();
699 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
700 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
701 // Offset is the sum of all previous structure fields.
702 for (uint64_t F = 0; F<FieldIndex; ++F)
703 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
705 printSimpleInstruction("add");
707 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
708 Size = TD->getTypeAllocSize(SeqTy->getElementType());
710 Size = TD->getTypeAllocSize(*I);
712 // Add offset of current element to stack top.
713 if (!isZeroValue(IndexValue)) {
714 // Constant optimization.
715 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
716 if (C->getValue().isNegative()) {
717 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
718 printSimpleInstruction("sub");
721 printPtrLoad(C->getZExtValue()*Size);
724 printValuePtrLoad(IndexValue);
725 printSimpleInstruction("mul");
727 printSimpleInstruction("add");
733 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
734 const Instruction* Inst,
737 if (Ty->isVarArg()) Tmp += "vararg ";
738 // Name and return type.
739 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
740 // Function argument type list.
741 unsigned NumParams = Ty->getNumParams();
742 for (unsigned I = 0; I!=NumParams; ++I) {
743 if (I!=0) Tmp += ",";
744 Tmp += getTypeName(Ty->getParamType(I));
746 // CLR needs to know the exact amount of parameters received by vararg
747 // function, because caller cleans the stack.
748 if (Ty->isVarArg() && Inst) {
749 // Origin to function arguments in "CallInst" or "InvokeInst".
750 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
751 // Print variable argument types.
752 unsigned NumOperands = Inst->getNumOperands()-Org;
753 if (NumParams<NumOperands) {
754 if (NumParams!=0) Tmp += ", ";
756 for (unsigned J = NumParams; J!=NumOperands; ++J) {
757 if (J!=NumParams) Tmp += ", ";
758 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
766 void MSILWriter::printFunctionCall(const Value* FnVal,
767 const Instruction* Inst) {
768 // Get function calling convention.
769 std::string Name = "";
770 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
771 Name = getConvModopt(Call->getCallingConv());
772 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
773 Name = getConvModopt(Invoke->getCallingConv());
775 cerr << "Instruction = " << Inst->getName() << '\n';
776 assert(0 && "Need \"Invoke\" or \"Call\" instruction only");
778 if (const Function* F = dyn_cast<Function>(FnVal)) {
780 Name += getValueName(F);
781 printSimpleInstruction("call",
782 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
784 // Indirect function call.
785 const PointerType* PTy = cast<PointerType>(FnVal->getType());
786 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
787 // Load function address.
788 printValueLoad(FnVal);
789 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
794 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
796 switch (Inst->getIntrinsicID()) {
797 case Intrinsic::vastart:
798 Name = getValueName(Inst->getOperand(1));
799 Name.insert(Name.length()-1,"$valist");
800 // Obtain the argument handle.
801 printSimpleInstruction("ldloca",Name.c_str());
802 printSimpleInstruction("arglist");
803 printSimpleInstruction("call",
804 "instance void [mscorlib]System.ArgIterator::.ctor"
805 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
806 // Save as pointer type "void*"
807 printValueLoad(Inst->getOperand(1));
808 printSimpleInstruction("ldloca",Name.c_str());
809 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
811 case Intrinsic::vaend:
812 // Close argument list handle.
813 printIndirectLoad(Inst->getOperand(1));
814 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
816 case Intrinsic::vacopy:
817 // Copy "ArgIterator" valuetype.
818 printIndirectLoad(Inst->getOperand(1));
819 printIndirectLoad(Inst->getOperand(2));
820 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
823 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
824 assert(0 && "Invalid intrinsic function");
829 void MSILWriter::printCallInstruction(const Instruction* Inst) {
830 if (isa<IntrinsicInst>(Inst)) {
831 // Handle intrinsic function.
832 printIntrinsicCall(cast<IntrinsicInst>(Inst));
834 // Load arguments to stack and call function.
835 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
836 printValueLoad(Inst->getOperand(I));
837 printFunctionCall(Inst->getOperand(0),Inst);
842 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
843 const Value* Right) {
845 case ICmpInst::ICMP_EQ:
846 printBinaryInstruction("ceq",Left,Right);
848 case ICmpInst::ICMP_NE:
849 // Emulate = not neg (Op1 eq Op2)
850 printBinaryInstruction("ceq",Left,Right);
851 printSimpleInstruction("neg");
852 printSimpleInstruction("not");
854 case ICmpInst::ICMP_ULE:
855 case ICmpInst::ICMP_SLE:
856 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
857 printBinaryInstruction("ceq",Left,Right);
858 if (Predicate==ICmpInst::ICMP_ULE)
859 printBinaryInstruction("clt.un",Left,Right);
861 printBinaryInstruction("clt",Left,Right);
862 printSimpleInstruction("or");
864 case ICmpInst::ICMP_UGE:
865 case ICmpInst::ICMP_SGE:
866 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
867 printBinaryInstruction("ceq",Left,Right);
868 if (Predicate==ICmpInst::ICMP_UGE)
869 printBinaryInstruction("cgt.un",Left,Right);
871 printBinaryInstruction("cgt",Left,Right);
872 printSimpleInstruction("or");
874 case ICmpInst::ICMP_ULT:
875 printBinaryInstruction("clt.un",Left,Right);
877 case ICmpInst::ICMP_SLT:
878 printBinaryInstruction("clt",Left,Right);
880 case ICmpInst::ICMP_UGT:
881 printBinaryInstruction("cgt.un",Left,Right);
882 case ICmpInst::ICMP_SGT:
883 printBinaryInstruction("cgt",Left,Right);
886 cerr << "Predicate = " << Predicate << '\n';
887 assert(0 && "Invalid icmp predicate");
892 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
893 const Value* Right) {
894 // FIXME: Correct comparison
895 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
897 case FCmpInst::FCMP_UGT:
898 // X > Y || llvm_fcmp_uno(X, Y)
899 printBinaryInstruction("cgt",Left,Right);
900 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
901 printSimpleInstruction("or");
903 case FCmpInst::FCMP_OGT:
905 printBinaryInstruction("cgt",Left,Right);
907 case FCmpInst::FCMP_UGE:
908 // X >= Y || llvm_fcmp_uno(X, Y)
909 printBinaryInstruction("ceq",Left,Right);
910 printBinaryInstruction("cgt",Left,Right);
911 printSimpleInstruction("or");
912 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
913 printSimpleInstruction("or");
915 case FCmpInst::FCMP_OGE:
917 printBinaryInstruction("ceq",Left,Right);
918 printBinaryInstruction("cgt",Left,Right);
919 printSimpleInstruction("or");
921 case FCmpInst::FCMP_ULT:
922 // X < Y || llvm_fcmp_uno(X, Y)
923 printBinaryInstruction("clt",Left,Right);
924 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
925 printSimpleInstruction("or");
927 case FCmpInst::FCMP_OLT:
929 printBinaryInstruction("clt",Left,Right);
931 case FCmpInst::FCMP_ULE:
932 // X <= Y || llvm_fcmp_uno(X, Y)
933 printBinaryInstruction("ceq",Left,Right);
934 printBinaryInstruction("clt",Left,Right);
935 printSimpleInstruction("or");
936 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
937 printSimpleInstruction("or");
939 case FCmpInst::FCMP_OLE:
941 printBinaryInstruction("ceq",Left,Right);
942 printBinaryInstruction("clt",Left,Right);
943 printSimpleInstruction("or");
945 case FCmpInst::FCMP_UEQ:
946 // X == Y || llvm_fcmp_uno(X, Y)
947 printBinaryInstruction("ceq",Left,Right);
948 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
949 printSimpleInstruction("or");
951 case FCmpInst::FCMP_OEQ:
953 printBinaryInstruction("ceq",Left,Right);
955 case FCmpInst::FCMP_UNE:
957 printBinaryInstruction("ceq",Left,Right);
958 printSimpleInstruction("neg");
959 printSimpleInstruction("not");
961 case FCmpInst::FCMP_ONE:
962 // X != Y && llvm_fcmp_ord(X, Y)
963 printBinaryInstruction("ceq",Left,Right);
964 printSimpleInstruction("not");
966 case FCmpInst::FCMP_ORD:
967 // return X == X && Y == Y
968 printBinaryInstruction("ceq",Left,Left);
969 printBinaryInstruction("ceq",Right,Right);
970 printSimpleInstruction("or");
972 case FCmpInst::FCMP_UNO:
974 printBinaryInstruction("ceq",Left,Left);
975 printSimpleInstruction("not");
976 printBinaryInstruction("ceq",Right,Right);
977 printSimpleInstruction("not");
978 printSimpleInstruction("or");
981 assert(0 && "Illegal FCmp predicate");
986 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
987 std::string Label = "leave$normal_"+utostr(getUniqID());
990 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
991 printValueLoad(Inst->getOperand(I));
992 // Print call instruction
993 printFunctionCall(Inst->getOperand(0),Inst);
994 // Save function result and leave "try" block
995 printValueSave(Inst);
996 printSimpleInstruction("leave",Label.c_str());
998 Out << "catch [mscorlib]System.Exception {\n";
999 // Redirect to unwind block
1000 printSimpleInstruction("pop");
1001 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1002 Out << "}\n" << Label << ":\n";
1003 // Redirect to continue block
1004 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1008 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1009 // FIXME: Emulate with IL "switch" instruction
1010 // Emulate = if () else if () else if () else ...
1011 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1012 printValueLoad(Inst->getCondition());
1013 printValueLoad(Inst->getCaseValue(I));
1014 printSimpleInstruction("ceq");
1015 // Condition jump to successor block
1016 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1018 // Jump to default block
1019 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1023 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1024 printIndirectLoad(Inst->getOperand(0));
1025 printSimpleInstruction("call",
1026 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1027 printSimpleInstruction("refanyval","void*");
1029 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1030 printSimpleInstruction(Name.c_str());
1034 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1035 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1036 // Constant optimization.
1037 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1038 printPtrLoad(CInt->getZExtValue()*Size);
1041 printValueLoad(Inst->getOperand(0));
1042 printSimpleInstruction("mul");
1044 printSimpleInstruction("localloc");
1048 void MSILWriter::printInstruction(const Instruction* Inst) {
1049 const Value *Left = 0, *Right = 0;
1050 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1051 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1052 // Print instruction
1053 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1054 switch (Inst->getOpcode()) {
1056 case Instruction::Ret:
1057 if (Inst->getNumOperands()) {
1058 printValueLoad(Left);
1059 printSimpleInstruction("ret");
1061 printSimpleInstruction("ret");
1063 case Instruction::Br:
1064 printBranchInstruction(cast<BranchInst>(Inst));
1067 case Instruction::Add:
1068 case Instruction::FAdd:
1069 printBinaryInstruction("add",Left,Right);
1071 case Instruction::Sub:
1072 case Instruction::FSub:
1073 printBinaryInstruction("sub",Left,Right);
1075 case Instruction::Mul:
1076 case Instruction::FMul:
1077 printBinaryInstruction("mul",Left,Right);
1079 case Instruction::UDiv:
1080 printBinaryInstruction("div.un",Left,Right);
1082 case Instruction::SDiv:
1083 case Instruction::FDiv:
1084 printBinaryInstruction("div",Left,Right);
1086 case Instruction::URem:
1087 printBinaryInstruction("rem.un",Left,Right);
1089 case Instruction::SRem:
1090 case Instruction::FRem:
1091 printBinaryInstruction("rem",Left,Right);
1094 case Instruction::ICmp:
1095 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1097 case Instruction::FCmp:
1098 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1101 case Instruction::And:
1102 printBinaryInstruction("and",Left,Right);
1104 case Instruction::Or:
1105 printBinaryInstruction("or",Left,Right);
1107 case Instruction::Xor:
1108 printBinaryInstruction("xor",Left,Right);
1110 case Instruction::Shl:
1111 printValueLoad(Left);
1112 printValueLoad(Right);
1113 printSimpleInstruction("conv.i4");
1114 printSimpleInstruction("shl");
1116 case Instruction::LShr:
1117 printValueLoad(Left);
1118 printValueLoad(Right);
1119 printSimpleInstruction("conv.i4");
1120 printSimpleInstruction("shr.un");
1122 case Instruction::AShr:
1123 printValueLoad(Left);
1124 printValueLoad(Right);
1125 printSimpleInstruction("conv.i4");
1126 printSimpleInstruction("shr");
1128 case Instruction::Select:
1129 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1131 case Instruction::Load:
1132 printIndirectLoad(Inst->getOperand(0));
1134 case Instruction::Store:
1135 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1137 case Instruction::Trunc:
1138 case Instruction::ZExt:
1139 case Instruction::SExt:
1140 case Instruction::FPTrunc:
1141 case Instruction::FPExt:
1142 case Instruction::UIToFP:
1143 case Instruction::SIToFP:
1144 case Instruction::FPToUI:
1145 case Instruction::FPToSI:
1146 case Instruction::PtrToInt:
1147 case Instruction::IntToPtr:
1148 case Instruction::BitCast:
1149 printCastInstruction(Inst->getOpcode(),Left,
1150 cast<CastInst>(Inst)->getDestTy());
1152 case Instruction::GetElementPtr:
1153 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1154 gep_type_end(Inst));
1156 case Instruction::Call:
1157 printCallInstruction(cast<CallInst>(Inst));
1159 case Instruction::Invoke:
1160 printInvokeInstruction(cast<InvokeInst>(Inst));
1162 case Instruction::Unwind:
1163 printSimpleInstruction("newobj",
1164 "instance void [mscorlib]System.Exception::.ctor()");
1165 printSimpleInstruction("throw");
1167 case Instruction::Switch:
1168 printSwitchInstruction(cast<SwitchInst>(Inst));
1170 case Instruction::Alloca:
1171 printAllocaInstruction(cast<AllocaInst>(Inst));
1173 case Instruction::Malloc:
1174 assert(0 && "LowerAllocationsPass used");
1176 case Instruction::Free:
1177 assert(0 && "LowerAllocationsPass used");
1179 case Instruction::Unreachable:
1180 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1181 printSimpleInstruction("newobj",
1182 "instance void [mscorlib]System.Exception::.ctor(string)");
1183 printSimpleInstruction("throw");
1185 case Instruction::VAArg:
1186 printVAArgInstruction(cast<VAArgInst>(Inst));
1189 cerr << "Instruction = " << Inst->getName() << '\n';
1190 assert(0 && "Unsupported instruction");
1195 void MSILWriter::printLoop(const Loop* L) {
1196 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1197 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1198 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1199 BasicBlock* BB = blocks[I];
1200 Loop* BBLoop = LInfo->getLoopFor(BB);
1202 printBasicBlock(BB);
1203 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1206 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1210 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1211 Out << getLabelName(BB) << ":\n";
1212 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1213 const Instruction* Inst = I;
1214 // Comment llvm original instruction
1215 // Out << "\n//" << *Inst << "\n";
1216 // Do not handle PHI instruction in current block
1217 if (Inst->getOpcode()==Instruction::PHI) continue;
1218 // Print instruction
1219 printInstruction(Inst);
1221 if (Inst->getType()!=Type::VoidTy) {
1222 // Do not save value after invoke, it done in "try" block
1223 if (Inst->getOpcode()==Instruction::Invoke) continue;
1224 printValueSave(Inst);
1230 void MSILWriter::printLocalVariables(const Function& F) {
1232 const Type* Ty = NULL;
1233 std::set<const Value*> Printed;
1234 const Value* VaList = NULL;
1235 unsigned StackDepth = 8;
1236 // Find local variables
1237 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1238 if (I->getOpcode()==Instruction::Call ||
1239 I->getOpcode()==Instruction::Invoke) {
1240 // Test stack depth.
1241 if (StackDepth<I->getNumOperands())
1242 StackDepth = I->getNumOperands();
1244 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1245 if (AI && !isa<GlobalVariable>(AI)) {
1246 // Local variable allocation.
1247 Ty = PointerType::getUnqual(AI->getAllocatedType());
1248 Name = getValueName(AI);
1249 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1250 } else if (I->getType()!=Type::VoidTy) {
1251 // Operation result.
1253 Name = getValueName(&*I);
1254 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1256 // Test on 'va_list' variable
1257 bool isVaList = false;
1258 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1259 // "va_list" as "va_arg" instruction operand.
1261 VaList = VaInst->getOperand(0);
1262 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1263 // "va_list" as intrinsic function operand.
1264 switch (Inst->getIntrinsicID()) {
1265 case Intrinsic::vastart:
1266 case Intrinsic::vaend:
1267 case Intrinsic::vacopy:
1269 VaList = Inst->getOperand(1);
1275 // Print "va_list" variable.
1276 if (isVaList && Printed.insert(VaList).second) {
1277 Name = getValueName(VaList);
1278 Name.insert(Name.length()-1,"$valist");
1279 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1283 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1287 void MSILWriter::printFunctionBody(const Function& F) {
1289 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1290 if (Loop *L = LInfo->getLoopFor(I)) {
1291 if (L->getHeader()==I && L->getParentLoop()==0)
1300 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1301 const Value *left = 0, *right = 0;
1302 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1303 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1304 // Print instruction
1305 switch (CE->getOpcode()) {
1306 case Instruction::Trunc:
1307 case Instruction::ZExt:
1308 case Instruction::SExt:
1309 case Instruction::FPTrunc:
1310 case Instruction::FPExt:
1311 case Instruction::UIToFP:
1312 case Instruction::SIToFP:
1313 case Instruction::FPToUI:
1314 case Instruction::FPToSI:
1315 case Instruction::PtrToInt:
1316 case Instruction::IntToPtr:
1317 case Instruction::BitCast:
1318 printCastInstruction(CE->getOpcode(),left,CE->getType());
1320 case Instruction::GetElementPtr:
1321 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1323 case Instruction::ICmp:
1324 printICmpInstruction(CE->getPredicate(),left,right);
1326 case Instruction::FCmp:
1327 printFCmpInstruction(CE->getPredicate(),left,right);
1329 case Instruction::Select:
1330 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1332 case Instruction::Add:
1333 case Instruction::FAdd:
1334 printBinaryInstruction("add",left,right);
1336 case Instruction::Sub:
1337 case Instruction::FSub:
1338 printBinaryInstruction("sub",left,right);
1340 case Instruction::Mul:
1341 case Instruction::FMul:
1342 printBinaryInstruction("mul",left,right);
1344 case Instruction::UDiv:
1345 printBinaryInstruction("div.un",left,right);
1347 case Instruction::SDiv:
1348 case Instruction::FDiv:
1349 printBinaryInstruction("div",left,right);
1351 case Instruction::URem:
1352 printBinaryInstruction("rem.un",left,right);
1354 case Instruction::SRem:
1355 case Instruction::FRem:
1356 printBinaryInstruction("rem",left,right);
1358 case Instruction::And:
1359 printBinaryInstruction("and",left,right);
1361 case Instruction::Or:
1362 printBinaryInstruction("or",left,right);
1364 case Instruction::Xor:
1365 printBinaryInstruction("xor",left,right);
1367 case Instruction::Shl:
1368 printBinaryInstruction("shl",left,right);
1370 case Instruction::LShr:
1371 printBinaryInstruction("shr.un",left,right);
1373 case Instruction::AShr:
1374 printBinaryInstruction("shr",left,right);
1377 cerr << "Expression = " << *CE << "\n";
1378 assert(0 && "Invalid constant expression");
1383 void MSILWriter::printStaticInitializerList() {
1384 // List of global variables with uninitialized fields.
1385 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1386 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1388 const std::vector<StaticInitializer>& InitList = VarI->second;
1389 if (InitList.empty()) continue;
1390 // For each uninitialized field.
1391 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1392 E = InitList.end(); I!=E; ++I) {
1393 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1394 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1395 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1396 // Load variable address
1397 printValueLoad(VarI->first);
1400 printPtrLoad(I->offset);
1401 printSimpleInstruction("add");
1404 printConstantExpr(CE);
1405 // Save result at offset
1406 std::string postfix = getTypePostfix(CE->getType(),true);
1407 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1408 postfix = "stind."+postfix;
1409 printSimpleInstruction(postfix.c_str());
1411 cerr << "Constant = " << *I->constant << '\n';
1412 assert(0 && "Invalid static initializer");
1419 void MSILWriter::printFunction(const Function& F) {
1420 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1421 Out << "\n.method static ";
1422 Out << (F.hasLocalLinkage() ? "private " : "public ");
1423 if (F.isVarArg()) Out << "vararg ";
1424 Out << getTypeName(F.getReturnType(),isSigned) <<
1425 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1428 unsigned ArgIdx = 1;
1429 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1431 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1432 if (I!=F.arg_begin()) Out << ", ";
1433 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1435 Out << ") cil managed\n";
1438 printLocalVariables(F);
1439 printFunctionBody(F);
1444 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1446 std::set<const Type*> Printed;
1447 for (std::set<const Type*>::const_iterator
1448 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1449 const Type* Ty = *UI;
1450 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1451 Name = getTypeName(Ty, false, true);
1452 // Type with no need to declare.
1454 // Print not duplicated type
1455 if (Printed.insert(Ty).second) {
1456 Out << ".class value explicit ansi sealed '" << Name << "'";
1457 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1464 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1465 unsigned int N = Ty->getPrimitiveSizeInBits();
1466 assert(N!=0 && "Invalid type in getBitWidth()");
1475 cerr << "Bits = " << N << '\n';
1476 assert(0 && "Unsupported integer width");
1478 return 0; // Not reached
1482 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1483 uint64_t TySize = 0;
1484 const Type* Ty = C->getType();
1485 // Print zero initialized constant.
1486 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1487 TySize = TD->getTypeAllocSize(C->getType());
1489 Out << "int8 (0) [" << TySize << "]";
1492 // Print constant initializer
1493 switch (Ty->getTypeID()) {
1494 case Type::IntegerTyID: {
1495 TySize = TD->getTypeAllocSize(Ty);
1496 const ConstantInt* Int = cast<ConstantInt>(C);
1497 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1500 case Type::FloatTyID:
1501 case Type::DoubleTyID: {
1502 TySize = TD->getTypeAllocSize(Ty);
1503 const ConstantFP* FP = cast<ConstantFP>(C);
1504 if (Ty->getTypeID() == Type::FloatTyID)
1506 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1509 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1512 case Type::ArrayTyID:
1513 case Type::VectorTyID:
1514 case Type::StructTyID:
1515 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1516 if (I!=0) Out << ",\n";
1517 printStaticConstant(C->getOperand(I),Offset);
1520 case Type::PointerTyID:
1521 TySize = TD->getTypeAllocSize(C->getType());
1522 // Initialize with global variable address
1523 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1524 std::string name = getValueName(G);
1525 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1527 // Dynamic initialization
1528 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1529 InitListPtr->push_back(StaticInitializer(C,Offset));
1530 // Null pointer initialization
1531 if (TySize==4) Out << "int32 (0)";
1532 else if (TySize==8) Out << "int64 (0)";
1533 else assert(0 && "Invalid pointer size");
1537 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1538 assert(0 && "Invalid type in printStaticConstant()");
1545 void MSILWriter::printStaticInitializer(const Constant* C,
1546 const std::string& Name) {
1547 switch (C->getType()->getTypeID()) {
1548 case Type::IntegerTyID:
1549 case Type::FloatTyID:
1550 case Type::DoubleTyID:
1551 Out << getPrimitiveTypeName(C->getType(), false);
1553 case Type::ArrayTyID:
1554 case Type::VectorTyID:
1555 case Type::StructTyID:
1556 case Type::PointerTyID:
1557 Out << getTypeName(C->getType());
1560 cerr << "Type = " << *C << "\n";
1561 assert(0 && "Invalid constant type");
1563 // Print initializer
1564 std::string label = Name;
1565 label.insert(label.length()-1,"$data");
1566 Out << Name << " at " << label << '\n';
1567 Out << ".data " << label << " = {\n";
1568 uint64_t offset = 0;
1569 printStaticConstant(C,offset);
1574 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1575 const Constant* C = G->getInitializer();
1576 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1579 InitListPtr = &StaticInitList[G];
1580 printStaticInitializer(C,getValueName(G));
1584 void MSILWriter::printGlobalVariables() {
1585 if (ModulePtr->global_empty()) return;
1586 Module::global_iterator I,E;
1587 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1588 // Variable definition
1589 Out << ".field static " << (I->isDeclaration() ? "public " :
1591 if (I->isDeclaration()) {
1592 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1594 printVariableDefinition(&*I);
1599 const char* MSILWriter::getLibraryName(const Function* F) {
1600 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1604 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1605 return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1609 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1610 unsigned CallingConv) {
1611 // TODO: Read *.def file with function and libraries definitions.
1612 return "MSVCRT.DLL";
1616 void MSILWriter::printExternals() {
1617 Module::const_iterator I,E;
1619 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1621 if (I->isIntrinsic()) continue;
1622 if (I->isDeclaration()) {
1623 const Function* F = I;
1624 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1626 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1627 Out << ".method static hidebysig pinvokeimpl(\""
1628 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1631 // External variables and static initialization.
1633 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1634 " native int LoadLibrary(string) preservesig {}\n"
1635 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1636 " native int GetProcAddress(native int, string) preservesig {}\n";
1638 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1641 "\tcall\tnative int LoadLibrary(string)\n"
1643 "\tcall\tnative int GetProcAddress(native int,string)\n"
1646 "\tldstr\t\"Can no import variable\"\n"
1647 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1652 ".method static private void $MSIL_Init() managed cil\n{\n";
1653 printStaticInitializerList();
1654 // Foreach global variable.
1655 for (Module::global_iterator I = ModulePtr->global_begin(),
1656 E = ModulePtr->global_end(); I!=E; ++I) {
1657 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1658 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1659 std::string Label = "not_null$_"+utostr(getUniqID());
1660 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1661 printSimpleInstruction("ldsflda",Tmp.c_str());
1662 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1663 Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1664 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1665 printIndirectSave(I->getType());
1667 printSimpleInstruction("ret");
1672 //===----------------------------------------------------------------------===//
1673 // External Interface declaration
1674 //===----------------------------------------------------------------------===//
1676 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
1677 CodeGenFileType FileType,
1678 CodeGenOpt::Level OptLevel)
1680 if (FileType != TargetMachine::AssemblyFile) return true;
1681 MSILWriter* Writer = new MSILWriter(o);
1682 PM.add(createGCLoweringPass());
1683 PM.add(createLowerAllocationsPass(true));
1684 // FIXME: Handle switch trougth native IL instruction "switch"
1685 PM.add(createLowerSwitchPass());
1686 PM.add(createCFGSimplificationPass());
1687 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1689 PM.add(createGCInfoDeleter());