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/ParameterAttributes.h"
20 #include "llvm/TypeSymbolTable.h"
21 #include "llvm/Analysis/ConstantsScanner.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/ADT/StringExtras.h"
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, std::ostream &Out,
38 CodeGenFileType FileType, bool Fast);
40 // This class always works, but shouldn't be the default in most cases.
41 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
43 virtual const TargetData *getTargetData() const { return &DataLayout; }
48 RegisterTarget<MSILTarget> X("msil", " MSIL backend");
50 bool MSILModule::runOnModule(Module &M) {
52 TD = &getAnalysis<TargetData>();
55 TypeSymbolTable& Table = M.getTypeSymbolTable();
56 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
57 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
58 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
61 std::set<const Type *>::iterator T = Types.find(I->second);
70 // Find unnamed types.
71 unsigned RenameCounter = 0;
72 for (std::set<const Type *>::const_iterator I = Types.begin(),
73 E = Types.end(); I!=E; ++I)
74 if (const StructType *STy = dyn_cast<StructType>(*I)) {
75 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
79 // Pointer for FunctionPass.
80 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
84 char MSILModule::ID = 0;
85 char MSILWriter::ID = 0;
87 bool MSILWriter::runOnFunction(Function &F) {
88 if (F.isDeclaration()) return false;
89 LInfo = &getAnalysis<LoopInfo>();
95 bool MSILWriter::doInitialization(Module &M) {
97 Mang = new Mangler(M);
98 Out << ".assembly extern mscorlib {}\n";
99 Out << ".assembly MSIL {}\n\n";
100 Out << "// External\n";
102 Out << "// Declarations\n";
103 printDeclarations(M.getTypeSymbolTable());
104 Out << "// Definitions\n";
105 printGlobalVariables();
106 Out << "// Startup code\n";
107 printModuleStartup();
112 bool MSILWriter::doFinalization(Module &M) {
118 void MSILWriter::printModuleStartup() {
120 ".method static public int32 $MSIL_Startup() {\n"
122 "\t.locals (native int i)\n"
123 "\t.locals (native int argc)\n"
124 "\t.locals (native int ptr)\n"
125 "\t.locals (void* argv)\n"
126 "\t.locals (string[] args)\n"
127 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
134 printPtrLoad(TD->getPointerSize());
149 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
150 "StringToHGlobalAnsi(string)\n"
154 printPtrLoad(TD->getPointerSize());
166 "\tcall void $MSIL_Init()\n";
168 // Call user 'main' function.
169 const Function* F = ModulePtr->getFunction("main");
170 if (!F || F->isDeclaration()) {
171 Out << "\tldc.i4.0\n\tret\n}\n";
175 std::string Args("");
176 Function::const_arg_iterator Arg1,Arg2;
178 switch (F->arg_size()) {
183 Arg1 = F->arg_begin();
184 if (Arg1->getType()->isInteger()) {
185 Out << "\tldloc\targc\n";
186 Args = getTypeName(Arg1->getType());
191 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
192 if (Arg1->getType()->isInteger() &&
193 Arg2->getType()->getTypeID() == Type::PointerTyID) {
194 Out << "\tldloc\targc\n\tldloc\targv\n";
195 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
203 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
204 if (BadSig || !F->getReturnType()->isInteger() && !RetVoid) {
205 Out << "\tldc.i4.0\n";
207 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
208 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
210 Out << "\tldc.i4.0\n";
212 Out << "\tconv.i4\n";
217 bool MSILWriter::isZeroValue(const Value* V) {
218 if (const Constant *C = dyn_cast<Constant>(V))
219 return C->isNullValue();
224 std::string MSILWriter::getValueName(const Value* V) {
225 // Name into the quotes allow control and space characters.
226 return "'"+Mang->getValueName(V)+"'";
230 std::string MSILWriter::getLabelName(const std::string& Name) {
231 if (Name.find('.')!=std::string::npos) {
232 std::string Tmp(Name);
233 // Replace unaccepable characters in the label name.
234 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
235 if (*I=='.') *I = '@';
242 std::string MSILWriter::getLabelName(const Value* V) {
243 return getLabelName(Mang->getValueName(V));
247 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
248 switch (CallingConvID) {
250 case CallingConv::Cold:
251 case CallingConv::Fast:
252 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
253 case CallingConv::X86_FastCall:
254 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
255 case CallingConv::X86_StdCall:
256 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
258 cerr << "CallingConvID = " << CallingConvID << '\n';
259 assert(0 && "Unsupported calling convention");
264 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
265 std::string Tmp = "";
266 const Type* ElemTy = Ty;
267 assert(Ty->getTypeID()==TyID && "Invalid type passed");
268 // Walk trought array element types.
270 // Multidimensional array.
271 if (ElemTy->getTypeID()==TyID) {
272 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
273 Tmp += utostr(ATy->getNumElements());
274 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
275 Tmp += utostr(VTy->getNumElements());
276 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
278 // Base element type found.
279 if (ElemTy->getTypeID()!=TyID) break;
282 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
286 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
287 unsigned NumBits = 0;
288 switch (Ty->getTypeID()) {
291 case Type::IntegerTyID:
292 NumBits = getBitWidth(Ty);
296 return "unsigned int"+utostr(NumBits)+" ";
297 return "int"+utostr(NumBits)+" ";
298 case Type::FloatTyID:
300 case Type::DoubleTyID:
303 cerr << "Type = " << *Ty << '\n';
304 assert(0 && "Invalid primitive type");
309 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
311 if (Ty->isPrimitiveType() || Ty->isInteger())
312 return getPrimitiveTypeName(Ty,isSigned);
313 // FIXME: "OpaqueType" support
314 switch (Ty->getTypeID()) {
315 case Type::PointerTyID:
317 case Type::StructTyID:
319 return ModulePtr->getTypeName(Ty);
320 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
321 case Type::ArrayTyID:
323 return getArrayTypeName(Ty->getTypeID(),Ty);
324 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
325 case Type::VectorTyID:
327 return getArrayTypeName(Ty->getTypeID(),Ty);
328 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
330 cerr << "Type = " << *Ty << '\n';
331 assert(0 && "Invalid type in getTypeName()");
336 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
338 if (isa<Argument>(V))
341 else if (const Function* F = dyn_cast<Function>(V))
342 return F->hasInternalLinkage() ? InternalVT : GlobalVT;
344 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
345 return G->hasInternalLinkage() ? InternalVT : GlobalVT;
347 else if (isa<Constant>(V))
348 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
354 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
356 unsigned NumBits = 0;
357 switch (Ty->getTypeID()) {
358 // Integer constant, expanding for stack operations.
359 case Type::IntegerTyID:
360 NumBits = getBitWidth(Ty);
361 // Expand integer value to "int32" or "int64".
362 if (Expand) return (NumBits<=32 ? "i4" : "i8");
363 if (NumBits==1) return "i1";
364 return (isSigned ? "i" : "u")+utostr(NumBits/8);
366 case Type::FloatTyID:
368 case Type::DoubleTyID:
370 case Type::PointerTyID:
371 return "i"+utostr(TD->getABITypeSize(Ty));
373 cerr << "TypeID = " << Ty->getTypeID() << '\n';
374 assert(0 && "Invalid type in TypeToPostfix()");
379 void MSILWriter::printConvToPtr() {
380 switch (ModulePtr->getPointerSize()) {
381 case Module::Pointer32:
382 printSimpleInstruction("conv.u4");
384 case Module::Pointer64:
385 printSimpleInstruction("conv.u8");
388 assert(0 && "Module use not supporting pointer size");
393 void MSILWriter::printPtrLoad(uint64_t N) {
394 switch (ModulePtr->getPointerSize()) {
395 case Module::Pointer32:
396 printSimpleInstruction("ldc.i4",utostr(N).c_str());
397 // FIXME: Need overflow test?
399 cerr << "Value = " << utostr(N) << '\n';
400 assert(0 && "32-bit pointer overflowed");
403 case Module::Pointer64:
404 printSimpleInstruction("ldc.i8",utostr(N).c_str());
407 assert(0 && "Module use not supporting pointer size");
412 void MSILWriter::printValuePtrLoad(const Value* V) {
418 void MSILWriter::printConstLoad(const Constant* C) {
419 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
421 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
422 if (CInt->isMinValue(true))
423 Out << CInt->getSExtValue();
425 Out << CInt->getZExtValue();
426 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
430 if (FP->getType()->getTypeID()==Type::FloatTyID) {
431 X = (uint32_t)FP->getValueAPF().convertToAPInt().getZExtValue();
434 X = FP->getValueAPF().convertToAPInt().getZExtValue();
437 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
438 } else if (isa<UndefValue>(C)) {
439 // Undefined constant value = NULL.
442 cerr << "Constant = " << *C << '\n';
443 assert(0 && "Invalid constant value");
449 void MSILWriter::printValueLoad(const Value* V) {
450 MSILWriter::ValueType Location = getValueLocation(V);
452 // Global variable or function address.
455 if (const Function* F = dyn_cast<Function>(V)) {
456 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
457 printSimpleInstruction("ldftn",
458 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
461 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
462 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
463 Tmp = "void* "+getValueName(V);
464 printSimpleInstruction("ldsfld",Tmp.c_str());
466 Tmp = getTypeName(ElemTy)+getValueName(V);
467 printSimpleInstruction("ldsflda",Tmp.c_str());
471 // Function argument.
473 printSimpleInstruction("ldarg",getValueName(V).c_str());
475 // Local function variable.
477 printSimpleInstruction("ldloc",getValueName(V).c_str());
481 if (isa<ConstantPointerNull>(V))
484 printConstLoad(cast<Constant>(V));
486 // Constant expression.
488 printConstantExpr(cast<ConstantExpr>(V));
491 cerr << "Value = " << *V << '\n';
492 assert(0 && "Invalid value location");
497 void MSILWriter::printValueSave(const Value* V) {
498 switch (getValueLocation(V)) {
500 printSimpleInstruction("starg",getValueName(V).c_str());
503 printSimpleInstruction("stloc",getValueName(V).c_str());
506 cerr << "Value = " << *V << '\n';
507 assert(0 && "Invalid value location");
512 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
513 const Value* Right) {
514 printValueLoad(Left);
515 printValueLoad(Right);
516 Out << '\t' << Name << '\n';
520 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
522 Out << '\t' << Inst << '\t' << Operand << '\n';
524 Out << '\t' << Inst << '\n';
528 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
529 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
530 isa<PHINode>(I); ++I) {
531 const PHINode* Phi = cast<PHINode>(I);
532 const Value* Val = Phi->getIncomingValueForBlock(Src);
533 if (isa<UndefValue>(Val)) continue;
540 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
541 const BasicBlock* TrueBB,
542 const BasicBlock* FalseBB) {
543 if (TrueBB==FalseBB) {
544 // "TrueBB" and "FalseBB" destination equals
545 printPHICopy(CurrBB,TrueBB);
546 printSimpleInstruction("pop");
547 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
548 } else if (FalseBB==NULL) {
549 // If "FalseBB" not used the jump have condition
550 printPHICopy(CurrBB,TrueBB);
551 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
552 } else if (TrueBB==NULL) {
553 // If "TrueBB" not used the jump is unconditional
554 printPHICopy(CurrBB,FalseBB);
555 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
557 // Copy PHI instructions for each block
558 std::string TmpLabel;
559 // Print PHI instructions for "TrueBB"
560 if (isa<PHINode>(TrueBB->begin())) {
561 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
562 printSimpleInstruction("brtrue",TmpLabel.c_str());
564 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
566 // Print PHI instructions for "FalseBB"
567 if (isa<PHINode>(FalseBB->begin())) {
568 printPHICopy(CurrBB,FalseBB);
569 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
571 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
573 if (isa<PHINode>(TrueBB->begin())) {
574 // Handle "TrueBB" PHI Copy
575 Out << TmpLabel << ":\n";
576 printPHICopy(CurrBB,TrueBB);
577 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
583 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
584 if (Inst->isUnconditional()) {
585 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
587 printValueLoad(Inst->getCondition());
588 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
589 Inst->getSuccessor(1));
594 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
595 const Value* VFalse) {
596 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
597 printValueLoad(VTrue);
598 printValueLoad(Cond);
599 printSimpleInstruction("brtrue",TmpLabel.c_str());
600 printSimpleInstruction("pop");
601 printValueLoad(VFalse);
602 Out << TmpLabel << ":\n";
606 void MSILWriter::printIndirectLoad(const Value* V) {
607 const Type* Ty = V->getType();
609 if (const PointerType* P = dyn_cast<PointerType>(Ty))
610 Ty = P->getElementType();
611 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
612 printSimpleInstruction(Tmp.c_str());
616 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
619 printIndirectSave(Val->getType());
623 void MSILWriter::printIndirectSave(const Type* Ty) {
624 // Instruction need signed postfix for any type.
625 std::string postfix = getTypePostfix(Ty, false);
626 if (*postfix.begin()=='u') *postfix.begin() = 'i';
627 postfix = "stind."+postfix;
628 printSimpleInstruction(postfix.c_str());
632 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
638 case Instruction::SExt:
639 case Instruction::SIToFP:
640 case Instruction::FPToSI:
641 Tmp = "conv."+getTypePostfix(Ty,false,true);
642 printSimpleInstruction(Tmp.c_str());
645 case Instruction::FPTrunc:
646 case Instruction::FPExt:
647 case Instruction::UIToFP:
648 case Instruction::Trunc:
649 case Instruction::ZExt:
650 case Instruction::FPToUI:
651 case Instruction::PtrToInt:
652 case Instruction::IntToPtr:
653 Tmp = "conv."+getTypePostfix(Ty,false);
654 printSimpleInstruction(Tmp.c_str());
657 case Instruction::BitCast:
658 // FIXME: meaning that ld*/st* instruction do not change data format.
661 cerr << "Opcode = " << Op << '\n';
662 assert(0 && "Invalid conversion instruction");
667 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
668 gep_type_iterator E) {
671 printValuePtrLoad(V);
672 // Calculate element offset.
675 const Value* IndexValue = I.getOperand();
676 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
677 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
678 // Offset is the sum of all previous structure fields.
679 for (uint64_t F = 0; F<FieldIndex; ++F)
680 Size += TD->getABITypeSize(StrucTy->getContainedType((unsigned)F));
682 printSimpleInstruction("add");
684 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
685 Size = TD->getABITypeSize(SeqTy->getElementType());
687 Size = TD->getABITypeSize(*I);
689 // Add offset of current element to stack top.
690 if (!isZeroValue(IndexValue)) {
691 // Constant optimization.
692 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
693 if (C->getValue().isNegative()) {
694 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
695 printSimpleInstruction("sub");
698 printPtrLoad(C->getZExtValue()*Size);
701 printValuePtrLoad(IndexValue);
702 printSimpleInstruction("mul");
704 printSimpleInstruction("add");
710 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
711 const Instruction* Inst,
714 if (Ty->isVarArg()) Tmp += "vararg ";
715 // Name and return type.
716 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
717 // Function argument type list.
718 unsigned NumParams = Ty->getNumParams();
719 for (unsigned I = 0; I!=NumParams; ++I) {
720 if (I!=0) Tmp += ",";
721 Tmp += getTypeName(Ty->getParamType(I));
723 // CLR needs to know the exact amount of parameters received by vararg
724 // function, because caller cleans the stack.
725 if (Ty->isVarArg() && Inst) {
726 // Origin to function arguments in "CallInst" or "InvokeInst".
727 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
728 // Print variable argument types.
729 unsigned NumOperands = Inst->getNumOperands()-Org;
730 if (NumParams<NumOperands) {
731 if (NumParams!=0) Tmp += ", ";
733 for (unsigned J = NumParams; J!=NumOperands; ++J) {
734 if (J!=NumParams) Tmp += ", ";
735 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
743 void MSILWriter::printFunctionCall(const Value* FnVal,
744 const Instruction* Inst) {
745 // Get function calling convention.
746 std::string Name = "";
747 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
748 Name = getConvModopt(Call->getCallingConv());
749 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
750 Name = getConvModopt(Invoke->getCallingConv());
752 cerr << "Instruction = " << Inst->getName() << '\n';
753 assert(0 && "Need \"Invoke\" or \"Call\" instruction only");
755 if (const Function* F = dyn_cast<Function>(FnVal)) {
757 Name += getValueName(F);
758 printSimpleInstruction("call",
759 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
761 // Indirect function call.
762 const PointerType* PTy = cast<PointerType>(FnVal->getType());
763 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
764 // Load function address.
765 printValueLoad(FnVal);
766 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
771 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
773 switch (Inst->getIntrinsicID()) {
774 case Intrinsic::vastart:
775 Name = getValueName(Inst->getOperand(1));
776 Name.insert(Name.length()-1,"$valist");
777 // Obtain the argument handle.
778 printSimpleInstruction("ldloca",Name.c_str());
779 printSimpleInstruction("arglist");
780 printSimpleInstruction("call",
781 "instance void [mscorlib]System.ArgIterator::.ctor"
782 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
783 // Save as pointer type "void*"
784 printValueLoad(Inst->getOperand(1));
785 printSimpleInstruction("ldloca",Name.c_str());
786 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
788 case Intrinsic::vaend:
789 // Close argument list handle.
790 printIndirectLoad(Inst->getOperand(1));
791 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
793 case Intrinsic::vacopy:
794 // Copy "ArgIterator" valuetype.
795 printIndirectLoad(Inst->getOperand(1));
796 printIndirectLoad(Inst->getOperand(2));
797 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
800 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
801 assert(0 && "Invalid intrinsic function");
806 void MSILWriter::printCallInstruction(const Instruction* Inst) {
807 if (isa<IntrinsicInst>(Inst)) {
808 // Handle intrinsic function.
809 printIntrinsicCall(cast<IntrinsicInst>(Inst));
811 // Load arguments to stack and call function.
812 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
813 printValueLoad(Inst->getOperand(I));
814 printFunctionCall(Inst->getOperand(0),Inst);
819 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
820 const Value* Right) {
822 case ICmpInst::ICMP_EQ:
823 printBinaryInstruction("ceq",Left,Right);
825 case ICmpInst::ICMP_NE:
826 // Emulate = not neg (Op1 eq Op2)
827 printBinaryInstruction("ceq",Left,Right);
828 printSimpleInstruction("neg");
829 printSimpleInstruction("not");
831 case ICmpInst::ICMP_ULE:
832 case ICmpInst::ICMP_SLE:
833 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
834 printBinaryInstruction("ceq",Left,Right);
835 if (Predicate==ICmpInst::ICMP_ULE)
836 printBinaryInstruction("clt.un",Left,Right);
838 printBinaryInstruction("clt",Left,Right);
839 printSimpleInstruction("or");
841 case ICmpInst::ICMP_UGE:
842 case ICmpInst::ICMP_SGE:
843 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
844 printBinaryInstruction("ceq",Left,Right);
845 if (Predicate==ICmpInst::ICMP_UGE)
846 printBinaryInstruction("cgt.un",Left,Right);
848 printBinaryInstruction("cgt",Left,Right);
849 printSimpleInstruction("or");
851 case ICmpInst::ICMP_ULT:
852 printBinaryInstruction("clt.un",Left,Right);
854 case ICmpInst::ICMP_SLT:
855 printBinaryInstruction("clt",Left,Right);
857 case ICmpInst::ICMP_UGT:
858 printBinaryInstruction("cgt.un",Left,Right);
859 case ICmpInst::ICMP_SGT:
860 printBinaryInstruction("cgt",Left,Right);
863 cerr << "Predicate = " << Predicate << '\n';
864 assert(0 && "Invalid icmp predicate");
869 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
870 const Value* Right) {
871 // FIXME: Correct comparison
872 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
874 case FCmpInst::FCMP_UGT:
875 // X > Y || llvm_fcmp_uno(X, Y)
876 printBinaryInstruction("cgt",Left,Right);
877 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
878 printSimpleInstruction("or");
880 case FCmpInst::FCMP_OGT:
882 printBinaryInstruction("cgt",Left,Right);
884 case FCmpInst::FCMP_UGE:
885 // X >= Y || llvm_fcmp_uno(X, Y)
886 printBinaryInstruction("ceq",Left,Right);
887 printBinaryInstruction("cgt",Left,Right);
888 printSimpleInstruction("or");
889 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
890 printSimpleInstruction("or");
892 case FCmpInst::FCMP_OGE:
894 printBinaryInstruction("ceq",Left,Right);
895 printBinaryInstruction("cgt",Left,Right);
896 printSimpleInstruction("or");
898 case FCmpInst::FCMP_ULT:
899 // X < Y || llvm_fcmp_uno(X, Y)
900 printBinaryInstruction("clt",Left,Right);
901 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
902 printSimpleInstruction("or");
904 case FCmpInst::FCMP_OLT:
906 printBinaryInstruction("clt",Left,Right);
908 case FCmpInst::FCMP_ULE:
909 // X <= Y || llvm_fcmp_uno(X, Y)
910 printBinaryInstruction("ceq",Left,Right);
911 printBinaryInstruction("clt",Left,Right);
912 printSimpleInstruction("or");
913 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
914 printSimpleInstruction("or");
916 case FCmpInst::FCMP_OLE:
918 printBinaryInstruction("ceq",Left,Right);
919 printBinaryInstruction("clt",Left,Right);
920 printSimpleInstruction("or");
922 case FCmpInst::FCMP_UEQ:
923 // X == Y || llvm_fcmp_uno(X, Y)
924 printBinaryInstruction("ceq",Left,Right);
925 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
926 printSimpleInstruction("or");
928 case FCmpInst::FCMP_OEQ:
930 printBinaryInstruction("ceq",Left,Right);
932 case FCmpInst::FCMP_UNE:
934 printBinaryInstruction("ceq",Left,Right);
935 printSimpleInstruction("neg");
936 printSimpleInstruction("not");
938 case FCmpInst::FCMP_ONE:
939 // X != Y && llvm_fcmp_ord(X, Y)
940 printBinaryInstruction("ceq",Left,Right);
941 printSimpleInstruction("not");
943 case FCmpInst::FCMP_ORD:
944 // return X == X && Y == Y
945 printBinaryInstruction("ceq",Left,Left);
946 printBinaryInstruction("ceq",Right,Right);
947 printSimpleInstruction("or");
949 case FCmpInst::FCMP_UNO:
951 printBinaryInstruction("ceq",Left,Left);
952 printSimpleInstruction("not");
953 printBinaryInstruction("ceq",Right,Right);
954 printSimpleInstruction("not");
955 printSimpleInstruction("or");
958 assert(0 && "Illegal FCmp predicate");
963 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
964 std::string Label = "leave$normal_"+utostr(getUniqID());
967 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
968 printValueLoad(Inst->getOperand(I));
969 // Print call instruction
970 printFunctionCall(Inst->getOperand(0),Inst);
971 // Save function result and leave "try" block
972 printValueSave(Inst);
973 printSimpleInstruction("leave",Label.c_str());
975 Out << "catch [mscorlib]System.Exception {\n";
976 // Redirect to unwind block
977 printSimpleInstruction("pop");
978 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
979 Out << "}\n" << Label << ":\n";
980 // Redirect to continue block
981 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
985 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
986 // FIXME: Emulate with IL "switch" instruction
987 // Emulate = if () else if () else if () else ...
988 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
989 printValueLoad(Inst->getCondition());
990 printValueLoad(Inst->getCaseValue(I));
991 printSimpleInstruction("ceq");
992 // Condition jump to successor block
993 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
995 // Jump to default block
996 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1000 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1001 printIndirectLoad(Inst->getOperand(0));
1002 printSimpleInstruction("call",
1003 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1004 printSimpleInstruction("refanyval","void*");
1006 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1007 printSimpleInstruction(Name.c_str());
1011 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1012 uint64_t Size = TD->getABITypeSize(Inst->getAllocatedType());
1013 // Constant optimization.
1014 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1015 printPtrLoad(CInt->getZExtValue()*Size);
1018 printValueLoad(Inst->getOperand(0));
1019 printSimpleInstruction("mul");
1021 printSimpleInstruction("localloc");
1025 void MSILWriter::printInstruction(const Instruction* Inst) {
1026 const Value *Left = 0, *Right = 0;
1027 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1028 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1029 // Print instruction
1030 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1031 switch (Inst->getOpcode()) {
1033 case Instruction::Ret:
1034 if (Inst->getNumOperands()) {
1035 printValueLoad(Left);
1036 printSimpleInstruction("ret");
1038 printSimpleInstruction("ret");
1040 case Instruction::Br:
1041 printBranchInstruction(cast<BranchInst>(Inst));
1044 case Instruction::Add:
1045 printBinaryInstruction("add",Left,Right);
1047 case Instruction::Sub:
1048 printBinaryInstruction("sub",Left,Right);
1050 case Instruction::Mul:
1051 printBinaryInstruction("mul",Left,Right);
1053 case Instruction::UDiv:
1054 printBinaryInstruction("div.un",Left,Right);
1056 case Instruction::SDiv:
1057 case Instruction::FDiv:
1058 printBinaryInstruction("div",Left,Right);
1060 case Instruction::URem:
1061 printBinaryInstruction("rem.un",Left,Right);
1063 case Instruction::SRem:
1064 case Instruction::FRem:
1065 printBinaryInstruction("rem",Left,Right);
1068 case Instruction::ICmp:
1069 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1071 case Instruction::FCmp:
1072 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1075 case Instruction::And:
1076 printBinaryInstruction("and",Left,Right);
1078 case Instruction::Or:
1079 printBinaryInstruction("or",Left,Right);
1081 case Instruction::Xor:
1082 printBinaryInstruction("xor",Left,Right);
1084 case Instruction::Shl:
1085 printValueLoad(Left);
1086 printValueLoad(Right);
1087 printSimpleInstruction("conv.i4");
1088 printSimpleInstruction("shl");
1090 case Instruction::LShr:
1091 printValueLoad(Left);
1092 printValueLoad(Right);
1093 printSimpleInstruction("conv.i4");
1094 printSimpleInstruction("shr.un");
1096 case Instruction::AShr:
1097 printValueLoad(Left);
1098 printValueLoad(Right);
1099 printSimpleInstruction("conv.i4");
1100 printSimpleInstruction("shr");
1102 case Instruction::Select:
1103 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1105 case Instruction::Load:
1106 printIndirectLoad(Inst->getOperand(0));
1108 case Instruction::Store:
1109 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1111 case Instruction::Trunc:
1112 case Instruction::ZExt:
1113 case Instruction::SExt:
1114 case Instruction::FPTrunc:
1115 case Instruction::FPExt:
1116 case Instruction::UIToFP:
1117 case Instruction::SIToFP:
1118 case Instruction::FPToUI:
1119 case Instruction::FPToSI:
1120 case Instruction::PtrToInt:
1121 case Instruction::IntToPtr:
1122 case Instruction::BitCast:
1123 printCastInstruction(Inst->getOpcode(),Left,
1124 cast<CastInst>(Inst)->getDestTy());
1126 case Instruction::GetElementPtr:
1127 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1128 gep_type_end(Inst));
1130 case Instruction::Call:
1131 printCallInstruction(cast<CallInst>(Inst));
1133 case Instruction::Invoke:
1134 printInvokeInstruction(cast<InvokeInst>(Inst));
1136 case Instruction::Unwind:
1137 printSimpleInstruction("newobj",
1138 "instance void [mscorlib]System.Exception::.ctor()");
1139 printSimpleInstruction("throw");
1141 case Instruction::Switch:
1142 printSwitchInstruction(cast<SwitchInst>(Inst));
1144 case Instruction::Alloca:
1145 printAllocaInstruction(cast<AllocaInst>(Inst));
1147 case Instruction::Malloc:
1148 assert(0 && "LowerAllocationsPass used");
1150 case Instruction::Free:
1151 assert(0 && "LowerAllocationsPass used");
1153 case Instruction::Unreachable:
1154 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1155 printSimpleInstruction("newobj",
1156 "instance void [mscorlib]System.Exception::.ctor(string)");
1157 printSimpleInstruction("throw");
1159 case Instruction::VAArg:
1160 printVAArgInstruction(cast<VAArgInst>(Inst));
1163 cerr << "Instruction = " << Inst->getName() << '\n';
1164 assert(0 && "Unsupported instruction");
1169 void MSILWriter::printLoop(const Loop* L) {
1170 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1171 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1172 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1173 BasicBlock* BB = blocks[I];
1174 Loop* BBLoop = LInfo->getLoopFor(BB);
1176 printBasicBlock(BB);
1177 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1180 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1184 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1185 Out << getLabelName(BB) << ":\n";
1186 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1187 const Instruction* Inst = I;
1188 // Comment llvm original instruction
1189 Out << "\n//" << *Inst << "\n";
1190 // Do not handle PHI instruction in current block
1191 if (Inst->getOpcode()==Instruction::PHI) continue;
1192 // Print instruction
1193 printInstruction(Inst);
1195 if (Inst->getType()!=Type::VoidTy) {
1196 // Do not save value after invoke, it done in "try" block
1197 if (Inst->getOpcode()==Instruction::Invoke) continue;
1198 printValueSave(Inst);
1204 void MSILWriter::printLocalVariables(const Function& F) {
1206 const Type* Ty = NULL;
1207 std::set<const Value*> Printed;
1208 const Value* VaList = NULL;
1209 unsigned StackDepth = 8;
1210 // Find local variables
1211 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1212 if (I->getOpcode()==Instruction::Call ||
1213 I->getOpcode()==Instruction::Invoke) {
1214 // Test stack depth.
1215 if (StackDepth<I->getNumOperands())
1216 StackDepth = I->getNumOperands();
1218 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1219 if (AI && !isa<GlobalVariable>(AI)) {
1220 // Local variable allocation.
1221 Ty = PointerType::getUnqual(AI->getAllocatedType());
1222 Name = getValueName(AI);
1223 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1224 } else if (I->getType()!=Type::VoidTy) {
1225 // Operation result.
1227 Name = getValueName(&*I);
1228 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1230 // Test on 'va_list' variable
1231 bool isVaList = false;
1232 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1233 // "va_list" as "va_arg" instruction operand.
1235 VaList = VaInst->getOperand(0);
1236 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1237 // "va_list" as intrinsic function operand.
1238 switch (Inst->getIntrinsicID()) {
1239 case Intrinsic::vastart:
1240 case Intrinsic::vaend:
1241 case Intrinsic::vacopy:
1243 VaList = Inst->getOperand(1);
1249 // Print "va_list" variable.
1250 if (isVaList && Printed.insert(VaList).second) {
1251 Name = getValueName(VaList);
1252 Name.insert(Name.length()-1,"$valist");
1253 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1257 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1261 void MSILWriter::printFunctionBody(const Function& F) {
1263 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1264 if (Loop *L = LInfo->getLoopFor(I)) {
1265 if (L->getHeader()==I && L->getParentLoop()==0)
1274 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1275 const Value *left = 0, *right = 0;
1276 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1277 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1278 // Print instruction
1279 switch (CE->getOpcode()) {
1280 case Instruction::Trunc:
1281 case Instruction::ZExt:
1282 case Instruction::SExt:
1283 case Instruction::FPTrunc:
1284 case Instruction::FPExt:
1285 case Instruction::UIToFP:
1286 case Instruction::SIToFP:
1287 case Instruction::FPToUI:
1288 case Instruction::FPToSI:
1289 case Instruction::PtrToInt:
1290 case Instruction::IntToPtr:
1291 case Instruction::BitCast:
1292 printCastInstruction(CE->getOpcode(),left,CE->getType());
1294 case Instruction::GetElementPtr:
1295 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1297 case Instruction::ICmp:
1298 printICmpInstruction(CE->getPredicate(),left,right);
1300 case Instruction::FCmp:
1301 printFCmpInstruction(CE->getPredicate(),left,right);
1303 case Instruction::Select:
1304 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1306 case Instruction::Add:
1307 printBinaryInstruction("add",left,right);
1309 case Instruction::Sub:
1310 printBinaryInstruction("sub",left,right);
1312 case Instruction::Mul:
1313 printBinaryInstruction("mul",left,right);
1315 case Instruction::UDiv:
1316 printBinaryInstruction("div.un",left,right);
1318 case Instruction::SDiv:
1319 case Instruction::FDiv:
1320 printBinaryInstruction("div",left,right);
1322 case Instruction::URem:
1323 printBinaryInstruction("rem.un",left,right);
1325 case Instruction::SRem:
1326 case Instruction::FRem:
1327 printBinaryInstruction("rem",left,right);
1329 case Instruction::And:
1330 printBinaryInstruction("and",left,right);
1332 case Instruction::Or:
1333 printBinaryInstruction("or",left,right);
1335 case Instruction::Xor:
1336 printBinaryInstruction("xor",left,right);
1338 case Instruction::Shl:
1339 printBinaryInstruction("shl",left,right);
1341 case Instruction::LShr:
1342 printBinaryInstruction("shr.un",left,right);
1344 case Instruction::AShr:
1345 printBinaryInstruction("shr",left,right);
1348 cerr << "Expression = " << *CE << "\n";
1349 assert(0 && "Invalid constant expression");
1354 void MSILWriter::printStaticInitializerList() {
1355 // List of global variables with uninitialized fields.
1356 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1357 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1359 const std::vector<StaticInitializer>& InitList = VarI->second;
1360 if (InitList.empty()) continue;
1361 // For each uninitialized field.
1362 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1363 E = InitList.end(); I!=E; ++I) {
1364 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1365 Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1366 utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1367 // Load variable address
1368 printValueLoad(VarI->first);
1371 printPtrLoad(I->offset);
1372 printSimpleInstruction("add");
1375 printConstantExpr(CE);
1376 // Save result at offset
1377 std::string postfix = getTypePostfix(CE->getType(),true);
1378 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1379 postfix = "stind."+postfix;
1380 printSimpleInstruction(postfix.c_str());
1382 cerr << "Constant = " << *I->constant << '\n';
1383 assert(0 && "Invalid static initializer");
1390 void MSILWriter::printFunction(const Function& F) {
1391 bool isSigned = F.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 = F.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->getABITypeSize(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->getABITypeSize(C->getType());
1458 Out << "int8 (0) [" << TySize << "]";
1461 // Print constant initializer
1462 switch (Ty->getTypeID()) {
1463 case Type::IntegerTyID: {
1464 TySize = TD->getABITypeSize(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->getABITypeSize(Ty);
1472 const ConstantFP* FP = cast<ConstantFP>(C);
1473 if (Ty->getTypeID() == Type::FloatTyID)
1475 (uint32_t)FP->getValueAPF().convertToAPInt().getZExtValue() << ')';
1478 FP->getValueAPF().convertToAPInt().getZExtValue() << ')';
1481 case Type::ArrayTyID:
1482 case Type::VectorTyID:
1483 case Type::StructTyID:
1484 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1485 if (I!=0) Out << ",\n";
1486 printStaticConstant(C->getOperand(I),Offset);
1489 case Type::PointerTyID:
1490 TySize = TD->getABITypeSize(C->getType());
1491 // Initialize with global variable address
1492 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1493 std::string name = getValueName(G);
1494 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1496 // Dynamic initialization
1497 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1498 InitListPtr->push_back(StaticInitializer(C,Offset));
1499 // Null pointer initialization
1500 if (TySize==4) Out << "int32 (0)";
1501 else if (TySize==8) Out << "int64 (0)";
1502 else assert(0 && "Invalid pointer size");
1506 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1507 assert(0 && "Invalid type in printStaticConstant()");
1514 void MSILWriter::printStaticInitializer(const Constant* C,
1515 const std::string& Name) {
1516 switch (C->getType()->getTypeID()) {
1517 case Type::IntegerTyID:
1518 case Type::FloatTyID:
1519 case Type::DoubleTyID:
1520 Out << getPrimitiveTypeName(C->getType(), false);
1522 case Type::ArrayTyID:
1523 case Type::VectorTyID:
1524 case Type::StructTyID:
1525 case Type::PointerTyID:
1526 Out << getTypeName(C->getType());
1529 cerr << "Type = " << *C << "\n";
1530 assert(0 && "Invalid constant type");
1532 // Print initializer
1533 std::string label = Name;
1534 label.insert(label.length()-1,"$data");
1535 Out << Name << " at " << label << '\n';
1536 Out << ".data " << label << " = {\n";
1537 uint64_t offset = 0;
1538 printStaticConstant(C,offset);
1543 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1544 const Constant* C = G->getInitializer();
1545 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1548 InitListPtr = &StaticInitList[G];
1549 printStaticInitializer(C,getValueName(G));
1553 void MSILWriter::printGlobalVariables() {
1554 if (ModulePtr->global_empty()) return;
1555 Module::global_iterator I,E;
1556 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1557 // Variable definition
1558 Out << ".field static " << (I->isDeclaration() ? "public " :
1560 if (I->isDeclaration()) {
1561 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1563 printVariableDefinition(&*I);
1568 const char* MSILWriter::getLibraryName(const Function* F) {
1569 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1573 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1574 return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1578 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1579 unsigned CallingConv) {
1580 // TODO: Read *.def file with function and libraries definitions.
1581 return "MSVCRT.DLL";
1585 void MSILWriter::printExternals() {
1586 Module::const_iterator I,E;
1588 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1590 if (I->isIntrinsic()) continue;
1591 if (I->isDeclaration()) {
1592 const Function* F = I;
1593 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1595 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1596 Out << ".method static hidebysig pinvokeimpl(\""
1597 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1600 // External variables and static initialization.
1602 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1603 " native int LoadLibrary(string) preservesig {}\n"
1604 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1605 " native int GetProcAddress(native int, string) preservesig {}\n";
1607 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1610 "\tcall\tnative int LoadLibrary(string)\n"
1612 "\tcall\tnative int GetProcAddress(native int,string)\n"
1615 "\tldstr\t\"Can no import variable\"\n"
1616 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1621 ".method static private void $MSIL_Init() managed cil\n{\n";
1622 printStaticInitializerList();
1623 // Foreach global variable.
1624 for (Module::global_iterator I = ModulePtr->global_begin(),
1625 E = ModulePtr->global_end(); I!=E; ++I) {
1626 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1627 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1628 std::string Label = "not_null$_"+utostr(getUniqID());
1629 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1630 printSimpleInstruction("ldsflda",Tmp.c_str());
1631 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1632 Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1633 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1634 printIndirectSave(I->getType());
1636 printSimpleInstruction("ret");
1641 //===----------------------------------------------------------------------===//
1642 // External Interface declaration
1643 //===----------------------------------------------------------------------===//
1645 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, std::ostream &o,
1646 CodeGenFileType FileType, bool Fast)
1648 if (FileType != TargetMachine::AssemblyFile) return true;
1649 MSILWriter* Writer = new MSILWriter(o);
1650 PM.add(createLowerGCPass());
1651 PM.add(createLowerAllocationsPass(true));
1652 // FIXME: Handle switch trougth native IL instruction "switch"
1653 PM.add(createLowerSwitchPass());
1654 PM.add(createCFGSimplificationPass());
1655 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));