2 // The LLVM Compiler Infrastructure
4 // This file was developed by Roman Samoilov and is distributed under
5 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This library converts LLVM code to MSIL code.
11 //===----------------------------------------------------------------------===//
13 #include "MSILWriter.h"
14 #include "llvm/CallingConv.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Intrinsics.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/ParameterAttributes.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"
28 // TargetMachine for the MSIL
29 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
30 const TargetData DataLayout; // Calculates type size & alignment
32 MSILTarget(const Module &M, const std::string &FS)
35 virtual bool WantsWholeFile() const { return true; }
36 virtual bool addPassesToEmitWholeFile(PassManager &PM, std::ostream &Out,
37 CodeGenFileType FileType, bool Fast);
39 // This class always works, but shouldn't be the default in most cases.
40 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
42 virtual const TargetData *getTargetData() const { return &DataLayout; }
47 RegisterTarget<MSILTarget> X("msil", " MSIL backend");
49 bool MSILModule::runOnModule(Module &M) {
51 TD = &getAnalysis<TargetData>();
54 TypeSymbolTable& Table = M.getTypeSymbolTable();
55 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
56 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
57 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
60 std::set<const Type *>::iterator T = Types.find(I->second);
69 // Find unnamed types.
70 unsigned RenameCounter = 0;
71 for (std::set<const Type *>::const_iterator I = Types.begin(),
72 E = Types.end(); I!=E; ++I)
73 if (const StructType *STy = dyn_cast<StructType>(*I)) {
74 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
78 // Pointer for FunctionPass.
79 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
83 char MSILModule::ID = 0;
84 char MSILWriter::ID = 0;
86 bool MSILWriter::runOnFunction(Function &F) {
87 if (F.isDeclaration()) return false;
88 LInfo = &getAnalysis<LoopInfo>();
94 bool MSILWriter::doInitialization(Module &M) {
96 Mang = new Mangler(M);
97 Out << ".assembly extern mscorlib {}\n";
98 Out << ".assembly MSIL {}\n\n";
99 Out << "// External\n";
101 Out << "// Declarations\n";
102 printDeclarations(M.getTypeSymbolTable());
103 Out << "// Definitions\n";
104 printGlobalVariables();
105 Out << "// Startup code\n";
106 printModuleStartup();
111 bool MSILWriter::doFinalization(Module &M) {
117 void MSILWriter::printModuleStartup() {
119 ".method static public int32 $MSIL_Startup() {\n"
121 "\t.locals (native int i)\n"
122 "\t.locals (native int argc)\n"
123 "\t.locals (native int ptr)\n"
124 "\t.locals (void* argv)\n"
125 "\t.locals (string[] args)\n"
126 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
133 printPtrLoad(TD->getPointerSize());
148 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
149 "StringToHGlobalAnsi(string)\n"
153 printPtrLoad(TD->getPointerSize());
165 "\tcall void $MSIL_Init()\n";
167 // Call user 'main' function.
168 const Function* F = ModulePtr->getFunction("main");
169 if (!F || F->isDeclaration()) {
170 Out << "\tldc.i4.0\n\tret\n}\n";
174 std::string Args("");
175 Function::const_arg_iterator Arg1,Arg2;
177 switch (F->arg_size()) {
182 Arg1 = F->arg_begin();
183 if (Arg1->getType()->isInteger()) {
184 Out << "\tldloc\targc\n";
185 Args = getTypeName(Arg1->getType());
190 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
191 if (Arg1->getType()->isInteger() &&
192 Arg2->getType()->getTypeID() == Type::PointerTyID) {
193 Out << "\tldloc\targc\n\tldloc\targv\n";
194 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
202 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
203 if (BadSig || !F->getReturnType()->isInteger() && !RetVoid) {
204 Out << "\tldc.i4.0\n";
206 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
207 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
209 Out << "\tldc.i4.0\n";
211 Out << "\tconv.i4\n";
216 bool MSILWriter::isZeroValue(const Value* V) {
217 if (const Constant *C = dyn_cast<Constant>(V))
218 return C->isNullValue();
223 std::string MSILWriter::getValueName(const Value* V) {
224 // Name into the quotes allow control and space characters.
225 return "'"+Mang->getValueName(V)+"'";
229 std::string MSILWriter::getLabelName(const std::string& Name) {
230 if (Name.find('.')!=std::string::npos) {
231 std::string Tmp(Name);
232 // Replace unaccepable characters in the label name.
233 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
234 if (*I=='.') *I = '@';
241 std::string MSILWriter::getLabelName(const Value* V) {
242 return getLabelName(Mang->getValueName(V));
246 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
247 switch (CallingConvID) {
249 case CallingConv::Cold:
250 case CallingConv::Fast:
251 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
252 case CallingConv::X86_FastCall:
253 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
254 case CallingConv::X86_StdCall:
255 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
257 cerr << "CallingConvID = " << CallingConvID << '\n';
258 assert(0 && "Unsupported calling convention");
263 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
264 std::string Tmp = "";
265 const Type* ElemTy = Ty;
266 assert(Ty->getTypeID()==TyID && "Invalid type passed");
267 // Walk trought array element types.
269 // Multidimensional array.
270 if (ElemTy->getTypeID()==TyID) {
271 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
272 Tmp += utostr(ATy->getNumElements());
273 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
274 Tmp += utostr(VTy->getNumElements());
275 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
277 // Base element type found.
278 if (ElemTy->getTypeID()!=TyID) break;
281 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
285 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
286 unsigned NumBits = 0;
287 switch (Ty->getTypeID()) {
290 case Type::IntegerTyID:
291 NumBits = getBitWidth(Ty);
295 return "unsigned int"+utostr(NumBits)+" ";
296 return "int"+utostr(NumBits)+" ";
297 case Type::FloatTyID:
299 case Type::DoubleTyID:
302 cerr << "Type = " << *Ty << '\n';
303 assert(0 && "Invalid primitive type");
308 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
310 if (Ty->isPrimitiveType() || Ty->isInteger())
311 return getPrimitiveTypeName(Ty,isSigned);
312 // FIXME: "OpaqueType" support
313 switch (Ty->getTypeID()) {
314 case Type::PointerTyID:
316 case Type::StructTyID:
318 return ModulePtr->getTypeName(Ty);
319 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
320 case Type::ArrayTyID:
322 return getArrayTypeName(Ty->getTypeID(),Ty);
323 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
324 case Type::VectorTyID:
326 return getArrayTypeName(Ty->getTypeID(),Ty);
327 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
329 cerr << "Type = " << *Ty << '\n';
330 assert(0 && "Invalid type in getTypeName()");
335 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
337 if (isa<Argument>(V))
340 else if (const Function* F = dyn_cast<Function>(V))
341 return F->hasInternalLinkage() ? InternalVT : GlobalVT;
343 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
344 return G->hasInternalLinkage() ? InternalVT : GlobalVT;
346 else if (isa<Constant>(V))
347 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
353 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
355 unsigned NumBits = 0;
356 switch (Ty->getTypeID()) {
357 // Integer constant, expanding for stack operations.
358 case Type::IntegerTyID:
359 NumBits = getBitWidth(Ty);
360 // Expand integer value to "int32" or "int64".
361 if (Expand) return (NumBits<=32 ? "i4" : "i8");
362 if (NumBits==1) return "i1";
363 return (isSigned ? "i" : "u")+utostr(NumBits/8);
365 case Type::FloatTyID:
367 case Type::DoubleTyID:
369 case Type::PointerTyID:
370 return "i"+utostr(TD->getTypeSize(Ty));
372 cerr << "TypeID = " << Ty->getTypeID() << '\n';
373 assert(0 && "Invalid type in TypeToPostfix()");
378 void MSILWriter::printConvToPtr() {
379 switch (ModulePtr->getPointerSize()) {
380 case Module::Pointer32:
381 printSimpleInstruction("conv.u4");
383 case Module::Pointer64:
384 printSimpleInstruction("conv.u8");
387 assert(0 && "Module use not supporting pointer size");
392 void MSILWriter::printPtrLoad(uint64_t N) {
393 switch (ModulePtr->getPointerSize()) {
394 case Module::Pointer32:
395 printSimpleInstruction("ldc.i4",utostr(N).c_str());
396 // FIXME: Need overflow test?
398 cerr << "Value = " << utostr(N) << '\n';
399 assert(0 && "32-bit pointer overflowed");
402 case Module::Pointer64:
403 printSimpleInstruction("ldc.i8",utostr(N).c_str());
406 assert(0 && "Module use not supporting pointer size");
411 void MSILWriter::printValuePtrLoad(const Value* V) {
417 void MSILWriter::printConstLoad(const Constant* C) {
418 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
420 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
421 if (CInt->isMinValue(true))
422 Out << CInt->getSExtValue();
424 Out << CInt->getZExtValue();
425 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
429 if (FP->getType()->getTypeID()==Type::FloatTyID) {
430 X = FloatToBits(FP->getValue());
433 X = DoubleToBits(FP->getValue());
436 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
437 } else if (isa<UndefValue>(C)) {
438 // Undefined constant value = NULL.
441 cerr << "Constant = " << *C << '\n';
442 assert(0 && "Invalid constant value");
448 void MSILWriter::printValueLoad(const Value* V) {
449 MSILWriter::ValueType Location = getValueLocation(V);
451 // Global variable or function address.
454 if (const Function* F = dyn_cast<Function>(V)) {
455 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
456 printSimpleInstruction("ldftn",
457 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
460 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
461 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
462 Tmp = "void* "+getValueName(V);
463 printSimpleInstruction("ldsfld",Tmp.c_str());
465 Tmp = getTypeName(ElemTy)+getValueName(V);
466 printSimpleInstruction("ldsflda",Tmp.c_str());
470 // Function argument.
472 printSimpleInstruction("ldarg",getValueName(V).c_str());
474 // Local function variable.
476 printSimpleInstruction("ldloc",getValueName(V).c_str());
480 if (isa<ConstantPointerNull>(V))
483 printConstLoad(cast<Constant>(V));
485 // Constant expression.
487 printConstantExpr(cast<ConstantExpr>(V));
490 cerr << "Value = " << *V << '\n';
491 assert(0 && "Invalid value location");
496 void MSILWriter::printValueSave(const Value* V) {
497 switch (getValueLocation(V)) {
499 printSimpleInstruction("starg",getValueName(V).c_str());
502 printSimpleInstruction("stloc",getValueName(V).c_str());
505 cerr << "Value = " << *V << '\n';
506 assert(0 && "Invalid value location");
511 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
512 const Value* Right) {
513 printValueLoad(Left);
514 printValueLoad(Right);
515 Out << '\t' << Name << '\n';
519 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
521 Out << '\t' << Inst << '\t' << Operand << '\n';
523 Out << '\t' << Inst << '\n';
527 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
528 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
529 isa<PHINode>(I); ++I) {
530 const PHINode* Phi = cast<PHINode>(I);
531 const Value* Val = Phi->getIncomingValueForBlock(Src);
532 if (isa<UndefValue>(Val)) continue;
539 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
540 const BasicBlock* TrueBB,
541 const BasicBlock* FalseBB) {
542 if (TrueBB==FalseBB) {
543 // "TrueBB" and "FalseBB" destination equals
544 printPHICopy(CurrBB,TrueBB);
545 printSimpleInstruction("pop");
546 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
547 } else if (FalseBB==NULL) {
548 // If "FalseBB" not used the jump have condition
549 printPHICopy(CurrBB,TrueBB);
550 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
551 } else if (TrueBB==NULL) {
552 // If "TrueBB" not used the jump is unconditional
553 printPHICopy(CurrBB,FalseBB);
554 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
556 // Copy PHI instructions for each block
557 std::string TmpLabel;
558 // Print PHI instructions for "TrueBB"
559 if (isa<PHINode>(TrueBB->begin())) {
560 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
561 printSimpleInstruction("brtrue",TmpLabel.c_str());
563 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
565 // Print PHI instructions for "FalseBB"
566 if (isa<PHINode>(FalseBB->begin())) {
567 printPHICopy(CurrBB,FalseBB);
568 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
570 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
572 if (isa<PHINode>(TrueBB->begin())) {
573 // Handle "TrueBB" PHI Copy
574 Out << TmpLabel << ":\n";
575 printPHICopy(CurrBB,TrueBB);
576 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
582 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
583 if (Inst->isUnconditional()) {
584 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
586 printValueLoad(Inst->getCondition());
587 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
588 Inst->getSuccessor(1));
593 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
594 const Value* VFalse) {
595 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
596 printValueLoad(VTrue);
597 printValueLoad(Cond);
598 printSimpleInstruction("brtrue",TmpLabel.c_str());
599 printSimpleInstruction("pop");
600 printValueLoad(VFalse);
601 Out << TmpLabel << ":\n";
605 void MSILWriter::printIndirectLoad(const Value* V) {
606 const Type* Ty = V->getType();
608 if (const PointerType* P = dyn_cast<PointerType>(Ty))
609 Ty = P->getElementType();
610 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
611 printSimpleInstruction(Tmp.c_str());
615 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
618 printIndirectSave(Val->getType());
622 void MSILWriter::printIndirectSave(const Type* Ty) {
623 // Instruction need signed postfix for any type.
624 std::string postfix = getTypePostfix(Ty, false);
625 if (*postfix.begin()=='u') *postfix.begin() = 'i';
626 postfix = "stind."+postfix;
627 printSimpleInstruction(postfix.c_str());
631 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
637 case Instruction::SExt:
638 case Instruction::SIToFP:
639 case Instruction::FPToSI:
640 Tmp = "conv."+getTypePostfix(Ty,false,true);
641 printSimpleInstruction(Tmp.c_str());
644 case Instruction::FPTrunc:
645 case Instruction::FPExt:
646 case Instruction::UIToFP:
647 case Instruction::Trunc:
648 case Instruction::ZExt:
649 case Instruction::FPToUI:
650 case Instruction::PtrToInt:
651 case Instruction::IntToPtr:
652 Tmp = "conv."+getTypePostfix(Ty,false);
653 printSimpleInstruction(Tmp.c_str());
656 case Instruction::BitCast:
657 // FIXME: meaning that ld*/st* instruction do not change data format.
660 cerr << "Opcode = " << Op << '\n';
661 assert(0 && "Invalid conversion instruction");
666 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
667 gep_type_iterator E) {
670 printValuePtrLoad(V);
671 // Calculate element offset.
674 const Value* IndexValue = I.getOperand();
675 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
676 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
677 // Offset is the sum of all previous structure fields.
678 for (uint64_t F = 0; F<FieldIndex; ++F)
679 Size += TD->getTypeSize(StrucTy->getContainedType((unsigned)F));
681 printSimpleInstruction("add");
683 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
684 Size = TD->getTypeSize(SeqTy->getElementType());
686 Size = TD->getTypeSize(*I);
688 // Add offset of current element to stack top.
689 if (!isZeroValue(IndexValue)) {
690 // Constant optimization.
691 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
692 if (C->getValue().isNegative()) {
693 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
694 printSimpleInstruction("sub");
697 printPtrLoad(C->getZExtValue()*Size);
700 printValuePtrLoad(IndexValue);
701 printSimpleInstruction("mul");
703 printSimpleInstruction("add");
709 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
710 const Instruction* Inst,
713 if (Ty->isVarArg()) Tmp += "vararg ";
714 // Name and return type.
715 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
716 // Function argument type list.
717 unsigned NumParams = Ty->getNumParams();
718 for (unsigned I = 0; I!=NumParams; ++I) {
719 if (I!=0) Tmp += ",";
720 Tmp += getTypeName(Ty->getParamType(I));
722 // CLR needs to know the exact amount of parameters received by vararg
723 // function, because caller cleans the stack.
724 if (Ty->isVarArg() && Inst) {
725 // Origin to function arguments in "CallInst" or "InvokeInst".
726 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
727 // Print variable argument types.
728 unsigned NumOperands = Inst->getNumOperands()-Org;
729 if (NumParams<NumOperands) {
730 if (NumParams!=0) Tmp += ", ";
732 for (unsigned J = NumParams; J!=NumOperands; ++J) {
733 if (J!=NumParams) Tmp += ", ";
734 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
742 void MSILWriter::printFunctionCall(const Value* FnVal,
743 const Instruction* Inst) {
744 // Get function calling convention.
745 std::string Name = "";
746 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
747 Name = getConvModopt(Call->getCallingConv());
748 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
749 Name = getConvModopt(Invoke->getCallingConv());
751 cerr << "Instruction = " << Inst->getName() << '\n';
752 assert(0 && "Need \"Invoke\" or \"Call\" instruction only");
754 if (const Function* F = dyn_cast<Function>(FnVal)) {
756 Name += getValueName(F);
757 printSimpleInstruction("call",
758 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
760 // Indirect function call.
761 const PointerType* PTy = cast<PointerType>(FnVal->getType());
762 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
763 // Load function address.
764 printValueLoad(FnVal);
765 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
770 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
772 switch (Inst->getIntrinsicID()) {
773 case Intrinsic::vastart:
774 Name = getValueName(Inst->getOperand(1));
775 Name.insert(Name.length()-1,"$valist");
776 // Obtain the argument handle.
777 printSimpleInstruction("ldloca",Name.c_str());
778 printSimpleInstruction("arglist");
779 printSimpleInstruction("call",
780 "instance void [mscorlib]System.ArgIterator::.ctor"
781 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
782 // Save as pointer type "void*"
783 printValueLoad(Inst->getOperand(1));
784 printSimpleInstruction("ldloca",Name.c_str());
785 printIndirectSave(PointerType::get(IntegerType::get(8)));
787 case Intrinsic::vaend:
788 // Close argument list handle.
789 printIndirectLoad(Inst->getOperand(1));
790 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
792 case Intrinsic::vacopy:
793 // Copy "ArgIterator" valuetype.
794 printIndirectLoad(Inst->getOperand(1));
795 printIndirectLoad(Inst->getOperand(2));
796 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
799 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
800 assert(0 && "Invalid intrinsic function");
805 void MSILWriter::printCallInstruction(const Instruction* Inst) {
806 if (isa<IntrinsicInst>(Inst)) {
807 // Handle intrinsic function.
808 printIntrinsicCall(cast<IntrinsicInst>(Inst));
810 // Load arguments to stack and call function.
811 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
812 printValueLoad(Inst->getOperand(I));
813 printFunctionCall(Inst->getOperand(0),Inst);
818 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
819 const Value* Right) {
821 case ICmpInst::ICMP_EQ:
822 printBinaryInstruction("ceq",Left,Right);
824 case ICmpInst::ICMP_NE:
825 // Emulate = not neg (Op1 eq Op2)
826 printBinaryInstruction("ceq",Left,Right);
827 printSimpleInstruction("neg");
828 printSimpleInstruction("not");
830 case ICmpInst::ICMP_ULE:
831 case ICmpInst::ICMP_SLE:
832 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
833 printBinaryInstruction("ceq",Left,Right);
834 if (Predicate==ICmpInst::ICMP_ULE)
835 printBinaryInstruction("clt.un",Left,Right);
837 printBinaryInstruction("clt",Left,Right);
838 printSimpleInstruction("or");
840 case ICmpInst::ICMP_UGE:
841 case ICmpInst::ICMP_SGE:
842 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
843 printBinaryInstruction("ceq",Left,Right);
844 if (Predicate==ICmpInst::ICMP_UGE)
845 printBinaryInstruction("cgt.un",Left,Right);
847 printBinaryInstruction("cgt",Left,Right);
848 printSimpleInstruction("or");
850 case ICmpInst::ICMP_ULT:
851 printBinaryInstruction("clt.un",Left,Right);
853 case ICmpInst::ICMP_SLT:
854 printBinaryInstruction("clt",Left,Right);
856 case ICmpInst::ICMP_UGT:
857 printBinaryInstruction("cgt.un",Left,Right);
858 case ICmpInst::ICMP_SGT:
859 printBinaryInstruction("cgt",Left,Right);
862 cerr << "Predicate = " << Predicate << '\n';
863 assert(0 && "Invalid icmp predicate");
868 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
869 const Value* Right) {
870 // FIXME: Correct comparison
871 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
873 case FCmpInst::FCMP_UGT:
874 // X > Y || llvm_fcmp_uno(X, Y)
875 printBinaryInstruction("cgt",Left,Right);
876 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
877 printSimpleInstruction("or");
879 case FCmpInst::FCMP_OGT:
881 printBinaryInstruction("cgt",Left,Right);
883 case FCmpInst::FCMP_UGE:
884 // X >= Y || llvm_fcmp_uno(X, Y)
885 printBinaryInstruction("ceq",Left,Right);
886 printBinaryInstruction("cgt",Left,Right);
887 printSimpleInstruction("or");
888 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
889 printSimpleInstruction("or");
891 case FCmpInst::FCMP_OGE:
893 printBinaryInstruction("ceq",Left,Right);
894 printBinaryInstruction("cgt",Left,Right);
895 printSimpleInstruction("or");
897 case FCmpInst::FCMP_ULT:
898 // X < Y || llvm_fcmp_uno(X, Y)
899 printBinaryInstruction("clt",Left,Right);
900 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
901 printSimpleInstruction("or");
903 case FCmpInst::FCMP_OLT:
905 printBinaryInstruction("clt",Left,Right);
907 case FCmpInst::FCMP_ULE:
908 // X <= Y || llvm_fcmp_uno(X, Y)
909 printBinaryInstruction("ceq",Left,Right);
910 printBinaryInstruction("clt",Left,Right);
911 printSimpleInstruction("or");
912 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
913 printSimpleInstruction("or");
915 case FCmpInst::FCMP_OLE:
917 printBinaryInstruction("ceq",Left,Right);
918 printBinaryInstruction("clt",Left,Right);
919 printSimpleInstruction("or");
921 case FCmpInst::FCMP_UEQ:
922 // X == Y || llvm_fcmp_uno(X, Y)
923 printBinaryInstruction("ceq",Left,Right);
924 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
925 printSimpleInstruction("or");
927 case FCmpInst::FCMP_OEQ:
929 printBinaryInstruction("ceq",Left,Right);
931 case FCmpInst::FCMP_UNE:
933 printBinaryInstruction("ceq",Left,Right);
934 printSimpleInstruction("neg");
935 printSimpleInstruction("not");
937 case FCmpInst::FCMP_ONE:
938 // X != Y && llvm_fcmp_ord(X, Y)
939 printBinaryInstruction("ceq",Left,Right);
940 printSimpleInstruction("not");
942 case FCmpInst::FCMP_ORD:
943 // return X == X && Y == Y
944 printBinaryInstruction("ceq",Left,Left);
945 printBinaryInstruction("ceq",Right,Right);
946 printSimpleInstruction("or");
948 case FCmpInst::FCMP_UNO:
950 printBinaryInstruction("ceq",Left,Left);
951 printSimpleInstruction("not");
952 printBinaryInstruction("ceq",Right,Right);
953 printSimpleInstruction("not");
954 printSimpleInstruction("or");
957 assert(0 && "Illegal FCmp predicate");
962 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
963 std::string Label = "leave$normal_"+utostr(getUniqID());
966 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
967 printValueLoad(Inst->getOperand(I));
968 // Print call instruction
969 printFunctionCall(Inst->getOperand(0),Inst);
970 // Save function result and leave "try" block
971 printValueSave(Inst);
972 printSimpleInstruction("leave",Label.c_str());
974 Out << "catch [mscorlib]System.Exception {\n";
975 // Redirect to unwind block
976 printSimpleInstruction("pop");
977 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
978 Out << "}\n" << Label << ":\n";
979 // Redirect to continue block
980 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
984 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
985 // FIXME: Emulate with IL "switch" instruction
986 // Emulate = if () else if () else if () else ...
987 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
988 printValueLoad(Inst->getCondition());
989 printValueLoad(Inst->getCaseValue(I));
990 printSimpleInstruction("ceq");
991 // Condition jump to successor block
992 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
994 // Jump to default block
995 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
999 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1000 printIndirectLoad(Inst->getOperand(0));
1001 printSimpleInstruction("call",
1002 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1003 printSimpleInstruction("refanyval","void*");
1004 std::string Name = "ldind."+getTypePostfix(PointerType::get(IntegerType::get(8)),false);
1005 printSimpleInstruction(Name.c_str());
1009 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1010 uint64_t Size = TD->getTypeSize(Inst->getAllocatedType());
1011 // Constant optimization.
1012 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1013 printPtrLoad(CInt->getZExtValue()*Size);
1016 printValueLoad(Inst->getOperand(0));
1017 printSimpleInstruction("mul");
1019 printSimpleInstruction("localloc");
1023 void MSILWriter::printInstruction(const Instruction* Inst) {
1024 const Value *Left = 0, *Right = 0;
1025 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1026 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1027 // Print instruction
1028 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1029 switch (Inst->getOpcode()) {
1031 case Instruction::Ret:
1032 if (Inst->getNumOperands()) {
1033 printValueLoad(Left);
1034 printSimpleInstruction("ret");
1036 printSimpleInstruction("ret");
1038 case Instruction::Br:
1039 printBranchInstruction(cast<BranchInst>(Inst));
1042 case Instruction::Add:
1043 printBinaryInstruction("add",Left,Right);
1045 case Instruction::Sub:
1046 printBinaryInstruction("sub",Left,Right);
1048 case Instruction::Mul:
1049 printBinaryInstruction("mul",Left,Right);
1051 case Instruction::UDiv:
1052 printBinaryInstruction("div.un",Left,Right);
1054 case Instruction::SDiv:
1055 case Instruction::FDiv:
1056 printBinaryInstruction("div",Left,Right);
1058 case Instruction::URem:
1059 printBinaryInstruction("rem.un",Left,Right);
1061 case Instruction::SRem:
1062 case Instruction::FRem:
1063 printBinaryInstruction("rem",Left,Right);
1066 case Instruction::ICmp:
1067 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1069 case Instruction::FCmp:
1070 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1073 case Instruction::And:
1074 printBinaryInstruction("and",Left,Right);
1076 case Instruction::Or:
1077 printBinaryInstruction("or",Left,Right);
1079 case Instruction::Xor:
1080 printBinaryInstruction("xor",Left,Right);
1082 case Instruction::Shl:
1083 printValueLoad(Left);
1084 printValueLoad(Right);
1085 printSimpleInstruction("conv.i4");
1086 printSimpleInstruction("shl");
1088 case Instruction::LShr:
1089 printValueLoad(Left);
1090 printValueLoad(Right);
1091 printSimpleInstruction("conv.i4");
1092 printSimpleInstruction("shr.un");
1094 case Instruction::AShr:
1095 printValueLoad(Left);
1096 printValueLoad(Right);
1097 printSimpleInstruction("conv.i4");
1098 printSimpleInstruction("shr");
1100 case Instruction::Select:
1101 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1103 case Instruction::Load:
1104 printIndirectLoad(Inst->getOperand(0));
1106 case Instruction::Store:
1107 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1109 case Instruction::Trunc:
1110 case Instruction::ZExt:
1111 case Instruction::SExt:
1112 case Instruction::FPTrunc:
1113 case Instruction::FPExt:
1114 case Instruction::UIToFP:
1115 case Instruction::SIToFP:
1116 case Instruction::FPToUI:
1117 case Instruction::FPToSI:
1118 case Instruction::PtrToInt:
1119 case Instruction::IntToPtr:
1120 case Instruction::BitCast:
1121 printCastInstruction(Inst->getOpcode(),Left,
1122 cast<CastInst>(Inst)->getDestTy());
1124 case Instruction::GetElementPtr:
1125 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1126 gep_type_end(Inst));
1128 case Instruction::Call:
1129 printCallInstruction(cast<CallInst>(Inst));
1131 case Instruction::Invoke:
1132 printInvokeInstruction(cast<InvokeInst>(Inst));
1134 case Instruction::Unwind:
1135 printSimpleInstruction("newobj",
1136 "instance void [mscorlib]System.Exception::.ctor()");
1137 printSimpleInstruction("throw");
1139 case Instruction::Switch:
1140 printSwitchInstruction(cast<SwitchInst>(Inst));
1142 case Instruction::Alloca:
1143 printAllocaInstruction(cast<AllocaInst>(Inst));
1145 case Instruction::Malloc:
1146 assert(0 && "LowerAllocationsPass used");
1148 case Instruction::Free:
1149 assert(0 && "LowerAllocationsPass used");
1151 case Instruction::Unreachable:
1152 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1153 printSimpleInstruction("newobj",
1154 "instance void [mscorlib]System.Exception::.ctor(string)");
1155 printSimpleInstruction("throw");
1157 case Instruction::VAArg:
1158 printVAArgInstruction(cast<VAArgInst>(Inst));
1161 cerr << "Instruction = " << Inst->getName() << '\n';
1162 assert(0 && "Unsupported instruction");
1167 void MSILWriter::printLoop(const Loop* L) {
1168 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1169 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1170 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1171 BasicBlock* BB = blocks[I];
1172 Loop* BBLoop = LInfo->getLoopFor(BB);
1174 printBasicBlock(BB);
1175 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1178 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1182 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1183 Out << getLabelName(BB) << ":\n";
1184 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1185 const Instruction* Inst = I;
1186 // Comment llvm original instruction
1187 Out << "\n//" << *Inst << "\n";
1188 // Do not handle PHI instruction in current block
1189 if (Inst->getOpcode()==Instruction::PHI) continue;
1190 // Print instruction
1191 printInstruction(Inst);
1193 if (Inst->getType()!=Type::VoidTy) {
1194 // Do not save value after invoke, it done in "try" block
1195 if (Inst->getOpcode()==Instruction::Invoke) continue;
1196 printValueSave(Inst);
1202 void MSILWriter::printLocalVariables(const Function& F) {
1204 const Type* Ty = NULL;
1205 std::set<const Value*> Printed;
1206 const Value* VaList = NULL;
1207 unsigned StackDepth = 8;
1208 // Find local variables
1209 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1210 if (I->getOpcode()==Instruction::Call ||
1211 I->getOpcode()==Instruction::Invoke) {
1212 // Test stack depth.
1213 if (StackDepth<I->getNumOperands())
1214 StackDepth = I->getNumOperands();
1216 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1217 if (AI && !isa<GlobalVariable>(AI)) {
1218 // Local variable allocation.
1219 Ty = PointerType::get(AI->getAllocatedType());
1220 Name = getValueName(AI);
1221 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1222 } else if (I->getType()!=Type::VoidTy) {
1223 // Operation result.
1225 Name = getValueName(&*I);
1226 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1228 // Test on 'va_list' variable
1229 bool isVaList = false;
1230 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1231 // "va_list" as "va_arg" instruction operand.
1233 VaList = VaInst->getOperand(0);
1234 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1235 // "va_list" as intrinsic function operand.
1236 switch (Inst->getIntrinsicID()) {
1237 case Intrinsic::vastart:
1238 case Intrinsic::vaend:
1239 case Intrinsic::vacopy:
1241 VaList = Inst->getOperand(1);
1247 // Print "va_list" variable.
1248 if (isVaList && Printed.insert(VaList).second) {
1249 Name = getValueName(VaList);
1250 Name.insert(Name.length()-1,"$valist");
1251 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1255 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1259 void MSILWriter::printFunctionBody(const Function& F) {
1261 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1262 if (Loop *L = LInfo->getLoopFor(I)) {
1263 if (L->getHeader()==I && L->getParentLoop()==0)
1272 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1273 const Value *left = 0, *right = 0;
1274 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1275 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1276 // Print instruction
1277 switch (CE->getOpcode()) {
1278 case Instruction::Trunc:
1279 case Instruction::ZExt:
1280 case Instruction::SExt:
1281 case Instruction::FPTrunc:
1282 case Instruction::FPExt:
1283 case Instruction::UIToFP:
1284 case Instruction::SIToFP:
1285 case Instruction::FPToUI:
1286 case Instruction::FPToSI:
1287 case Instruction::PtrToInt:
1288 case Instruction::IntToPtr:
1289 case Instruction::BitCast:
1290 printCastInstruction(CE->getOpcode(),left,CE->getType());
1292 case Instruction::GetElementPtr:
1293 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1295 case Instruction::ICmp:
1296 printICmpInstruction(CE->getPredicate(),left,right);
1298 case Instruction::FCmp:
1299 printFCmpInstruction(CE->getPredicate(),left,right);
1301 case Instruction::Select:
1302 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1304 case Instruction::Add:
1305 printBinaryInstruction("add",left,right);
1307 case Instruction::Sub:
1308 printBinaryInstruction("sub",left,right);
1310 case Instruction::Mul:
1311 printBinaryInstruction("mul",left,right);
1313 case Instruction::UDiv:
1314 printBinaryInstruction("div.un",left,right);
1316 case Instruction::SDiv:
1317 case Instruction::FDiv:
1318 printBinaryInstruction("div",left,right);
1320 case Instruction::URem:
1321 printBinaryInstruction("rem.un",left,right);
1323 case Instruction::SRem:
1324 case Instruction::FRem:
1325 printBinaryInstruction("rem",left,right);
1327 case Instruction::And:
1328 printBinaryInstruction("and",left,right);
1330 case Instruction::Or:
1331 printBinaryInstruction("or",left,right);
1333 case Instruction::Xor:
1334 printBinaryInstruction("xor",left,right);
1336 case Instruction::Shl:
1337 printBinaryInstruction("shl",left,right);
1339 case Instruction::LShr:
1340 printBinaryInstruction("shr.un",left,right);
1342 case Instruction::AShr:
1343 printBinaryInstruction("shr",left,right);
1346 cerr << "Expression = " << *CE << "\n";
1347 assert(0 && "Invalid constant expression");
1352 void MSILWriter::printStaticInitializerList() {
1353 // List of global variables with uninitialized fields.
1354 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1355 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1357 const std::vector<StaticInitializer>& InitList = VarI->second;
1358 if (InitList.empty()) continue;
1359 // For each uninitialized field.
1360 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1361 E = InitList.end(); I!=E; ++I) {
1362 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1363 Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1364 utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1365 // Load variable address
1366 printValueLoad(VarI->first);
1369 printPtrLoad(I->offset);
1370 printSimpleInstruction("add");
1373 printConstantExpr(CE);
1374 // Save result at offset
1375 std::string postfix = getTypePostfix(CE->getType(),true);
1376 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1377 postfix = "stind."+postfix;
1378 printSimpleInstruction(postfix.c_str());
1380 cerr << "Constant = " << *I->constant << '\n';
1381 assert(0 && "Invalid static initializer");
1388 void MSILWriter::printFunction(const Function& F) {
1389 const FunctionType* FTy = F.getFunctionType();
1390 const ParamAttrsList *Attrs = FTy->getParamAttrs();
1391 bool isSigned = Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt);
1392 Out << "\n.method static ";
1393 Out << (F.hasInternalLinkage() ? "private " : "public ");
1394 if (F.isVarArg()) Out << "vararg ";
1395 Out << getTypeName(F.getReturnType(),isSigned) <<
1396 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1399 unsigned ArgIdx = 1;
1400 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1402 isSigned = Attrs && Attrs->paramHasAttr(ArgIdx, ParamAttr::SExt);
1403 if (I!=F.arg_begin()) Out << ", ";
1404 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1406 Out << ") cil managed\n";
1409 printLocalVariables(F);
1410 printFunctionBody(F);
1415 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1417 std::set<const Type*> Printed;
1418 for (std::set<const Type*>::const_iterator
1419 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1420 const Type* Ty = *UI;
1421 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1422 Name = getTypeName(Ty, false, true);
1423 // Type with no need to declare.
1425 // Print not duplicated type
1426 if (Printed.insert(Ty).second) {
1427 Out << ".class value explicit ansi sealed '" << Name << "'";
1428 Out << " { .pack " << 1 << " .size " << TD->getTypeSize(Ty) << " }\n\n";
1434 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1435 unsigned int N = Ty->getPrimitiveSizeInBits();
1436 assert(N!=0 && "Invalid type in getBitWidth()");
1445 cerr << "Bits = " << N << '\n';
1446 assert(0 && "Unsupported integer width");
1451 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1452 uint64_t TySize = 0;
1453 const Type* Ty = C->getType();
1454 // Print zero initialized constant.
1455 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1456 TySize = TD->getTypeSize(C->getType());
1458 Out << "int8 (0) [" << TySize << "]";
1461 // Print constant initializer
1462 switch (Ty->getTypeID()) {
1463 case Type::IntegerTyID: {
1464 TySize = TD->getTypeSize(Ty);
1465 const ConstantInt* Int = cast<ConstantInt>(C);
1466 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1469 case Type::FloatTyID:
1470 case Type::DoubleTyID: {
1471 TySize = TD->getTypeSize(Ty);
1472 const ConstantFP* FP = cast<ConstantFP>(C);
1473 if (Ty->getTypeID() == Type::FloatTyID)
1474 Out << "int32 (" << FloatToBits(FP->getValue()) << ')';
1476 Out << "int64 (" << DoubleToBits(FP->getValue()) << ')';
1479 case Type::ArrayTyID:
1480 case Type::VectorTyID:
1481 case Type::StructTyID:
1482 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1483 if (I!=0) Out << ",\n";
1484 printStaticConstant(C->getOperand(I),Offset);
1487 case Type::PointerTyID:
1488 TySize = TD->getTypeSize(C->getType());
1489 // Initialize with global variable address
1490 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1491 std::string name = getValueName(G);
1492 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1494 // Dynamic initialization
1495 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1496 InitListPtr->push_back(StaticInitializer(C,Offset));
1497 // Null pointer initialization
1498 if (TySize==4) Out << "int32 (0)";
1499 else if (TySize==8) Out << "int64 (0)";
1500 else assert(0 && "Invalid pointer size");
1504 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1505 assert(0 && "Invalid type in printStaticConstant()");
1512 void MSILWriter::printStaticInitializer(const Constant* C,
1513 const std::string& Name) {
1514 switch (C->getType()->getTypeID()) {
1515 case Type::IntegerTyID:
1516 case Type::FloatTyID:
1517 case Type::DoubleTyID:
1518 Out << getPrimitiveTypeName(C->getType(), false);
1520 case Type::ArrayTyID:
1521 case Type::VectorTyID:
1522 case Type::StructTyID:
1523 case Type::PointerTyID:
1524 Out << getTypeName(C->getType());
1527 cerr << "Type = " << *C << "\n";
1528 assert(0 && "Invalid constant type");
1530 // Print initializer
1531 std::string label = Name;
1532 label.insert(label.length()-1,"$data");
1533 Out << Name << " at " << label << '\n';
1534 Out << ".data " << label << " = {\n";
1535 uint64_t offset = 0;
1536 printStaticConstant(C,offset);
1541 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1542 const Constant* C = G->getInitializer();
1543 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1546 InitListPtr = &StaticInitList[G];
1547 printStaticInitializer(C,getValueName(G));
1551 void MSILWriter::printGlobalVariables() {
1552 if (ModulePtr->global_empty()) return;
1553 Module::global_iterator I,E;
1554 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1555 // Variable definition
1556 Out << ".field static " << (I->isDeclaration() ? "public " :
1558 if (I->isDeclaration()) {
1559 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1561 printVariableDefinition(&*I);
1566 const char* MSILWriter::getLibraryName(const Function* F) {
1567 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1571 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1572 return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1576 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1577 unsigned CallingConv) {
1578 // TODO: Read *.def file with function and libraries definitions.
1579 return "MSVCRT.DLL";
1583 void MSILWriter::printExternals() {
1584 Module::const_iterator I,E;
1586 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1588 if (I->getIntrinsicID()) continue;
1589 if (I->isDeclaration()) {
1590 const Function* F = I;
1591 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1593 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1594 Out << ".method static hidebysig pinvokeimpl(\""
1595 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1598 // External variables and static initialization.
1600 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1601 " native int LoadLibrary(string) preservesig {}\n"
1602 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1603 " native int GetProcAddress(native int, string) preservesig {}\n";
1605 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1608 "\tcall\tnative int LoadLibrary(string)\n"
1610 "\tcall\tnative int GetProcAddress(native int,string)\n"
1613 "\tldstr\t\"Can no import variable\"\n"
1614 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1619 ".method static private void $MSIL_Init() managed cil\n{\n";
1620 printStaticInitializerList();
1621 // Foreach global variable.
1622 for (Module::global_iterator I = ModulePtr->global_begin(),
1623 E = ModulePtr->global_end(); I!=E; ++I) {
1624 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1625 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1626 std::string Label = "not_null$_"+utostr(getUniqID());
1627 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1628 printSimpleInstruction("ldsflda",Tmp.c_str());
1629 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1630 Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1631 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1632 printIndirectSave(I->getType());
1634 printSimpleInstruction("ret");
1639 //===----------------------------------------------------------------------===//
1640 // External Interface declaration
1641 //===----------------------------------------------------------------------===//
1643 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, std::ostream &o,
1644 CodeGenFileType FileType, bool Fast)
1646 if (FileType != TargetMachine::AssemblyFile) return true;
1647 MSILWriter* Writer = new MSILWriter(o);
1648 PM.add(createLowerGCPass());
1649 PM.add(createLowerAllocationsPass(true));
1650 // FIXME: Handle switch trougth native IL instruction "switch"
1651 PM.add(createLowerSwitchPass());
1652 PM.add(createCFGSimplificationPass());
1653 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));