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, 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 static 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");
261 return ""; // Not reached
265 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
266 std::string Tmp = "";
267 const Type* ElemTy = Ty;
268 assert(Ty->getTypeID()==TyID && "Invalid type passed");
269 // Walk trought array element types.
271 // Multidimensional array.
272 if (ElemTy->getTypeID()==TyID) {
273 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
274 Tmp += utostr(ATy->getNumElements());
275 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
276 Tmp += utostr(VTy->getNumElements());
277 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
279 // Base element type found.
280 if (ElemTy->getTypeID()!=TyID) break;
283 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
287 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
288 unsigned NumBits = 0;
289 switch (Ty->getTypeID()) {
292 case Type::IntegerTyID:
293 NumBits = getBitWidth(Ty);
297 return "unsigned int"+utostr(NumBits)+" ";
298 return "int"+utostr(NumBits)+" ";
299 case Type::FloatTyID:
301 case Type::DoubleTyID:
304 cerr << "Type = " << *Ty << '\n';
305 assert(0 && "Invalid primitive type");
307 return ""; // Not reached
311 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
313 if (Ty->isPrimitiveType() || Ty->isInteger())
314 return getPrimitiveTypeName(Ty,isSigned);
315 // FIXME: "OpaqueType" support
316 switch (Ty->getTypeID()) {
317 case Type::PointerTyID:
319 case Type::StructTyID:
321 return ModulePtr->getTypeName(Ty);
322 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
323 case Type::ArrayTyID:
325 return getArrayTypeName(Ty->getTypeID(),Ty);
326 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
327 case Type::VectorTyID:
329 return getArrayTypeName(Ty->getTypeID(),Ty);
330 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
332 cerr << "Type = " << *Ty << '\n';
333 assert(0 && "Invalid type in getTypeName()");
335 return ""; // Not reached
339 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
341 if (isa<Argument>(V))
344 else if (const Function* F = dyn_cast<Function>(V))
345 return F->hasInternalLinkage() ? InternalVT : GlobalVT;
347 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
348 return G->hasInternalLinkage() ? InternalVT : GlobalVT;
350 else if (isa<Constant>(V))
351 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
357 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
359 unsigned NumBits = 0;
360 switch (Ty->getTypeID()) {
361 // Integer constant, expanding for stack operations.
362 case Type::IntegerTyID:
363 NumBits = getBitWidth(Ty);
364 // Expand integer value to "int32" or "int64".
365 if (Expand) return (NumBits<=32 ? "i4" : "i8");
366 if (NumBits==1) return "i1";
367 return (isSigned ? "i" : "u")+utostr(NumBits/8);
369 case Type::FloatTyID:
371 case Type::DoubleTyID:
373 case Type::PointerTyID:
374 return "i"+utostr(TD->getABITypeSize(Ty));
376 cerr << "TypeID = " << Ty->getTypeID() << '\n';
377 assert(0 && "Invalid type in TypeToPostfix()");
379 return ""; // Not reached
383 void MSILWriter::printConvToPtr() {
384 switch (ModulePtr->getPointerSize()) {
385 case Module::Pointer32:
386 printSimpleInstruction("conv.u4");
388 case Module::Pointer64:
389 printSimpleInstruction("conv.u8");
392 assert(0 && "Module use not supporting pointer size");
397 void MSILWriter::printPtrLoad(uint64_t N) {
398 switch (ModulePtr->getPointerSize()) {
399 case Module::Pointer32:
400 printSimpleInstruction("ldc.i4",utostr(N).c_str());
401 // FIXME: Need overflow test?
403 cerr << "Value = " << utostr(N) << '\n';
404 assert(0 && "32-bit pointer overflowed");
407 case Module::Pointer64:
408 printSimpleInstruction("ldc.i8",utostr(N).c_str());
411 assert(0 && "Module use not supporting pointer size");
416 void MSILWriter::printValuePtrLoad(const Value* V) {
422 void MSILWriter::printConstLoad(const Constant* C) {
423 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
425 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
426 if (CInt->isMinValue(true))
427 Out << CInt->getSExtValue();
429 Out << CInt->getZExtValue();
430 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
434 if (FP->getType()->getTypeID()==Type::FloatTyID) {
435 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
438 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
441 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
442 } else if (isa<UndefValue>(C)) {
443 // Undefined constant value = NULL.
446 cerr << "Constant = " << *C << '\n';
447 assert(0 && "Invalid constant value");
453 void MSILWriter::printValueLoad(const Value* V) {
454 MSILWriter::ValueType Location = getValueLocation(V);
456 // Global variable or function address.
459 if (const Function* F = dyn_cast<Function>(V)) {
460 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
461 printSimpleInstruction("ldftn",
462 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
465 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
466 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
467 Tmp = "void* "+getValueName(V);
468 printSimpleInstruction("ldsfld",Tmp.c_str());
470 Tmp = getTypeName(ElemTy)+getValueName(V);
471 printSimpleInstruction("ldsflda",Tmp.c_str());
475 // Function argument.
477 printSimpleInstruction("ldarg",getValueName(V).c_str());
479 // Local function variable.
481 printSimpleInstruction("ldloc",getValueName(V).c_str());
485 if (isa<ConstantPointerNull>(V))
488 printConstLoad(cast<Constant>(V));
490 // Constant expression.
492 printConstantExpr(cast<ConstantExpr>(V));
495 cerr << "Value = " << *V << '\n';
496 assert(0 && "Invalid value location");
501 void MSILWriter::printValueSave(const Value* V) {
502 switch (getValueLocation(V)) {
504 printSimpleInstruction("starg",getValueName(V).c_str());
507 printSimpleInstruction("stloc",getValueName(V).c_str());
510 cerr << "Value = " << *V << '\n';
511 assert(0 && "Invalid value location");
516 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
517 const Value* Right) {
518 printValueLoad(Left);
519 printValueLoad(Right);
520 Out << '\t' << Name << '\n';
524 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
526 Out << '\t' << Inst << '\t' << Operand << '\n';
528 Out << '\t' << Inst << '\n';
532 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
533 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
534 isa<PHINode>(I); ++I) {
535 const PHINode* Phi = cast<PHINode>(I);
536 const Value* Val = Phi->getIncomingValueForBlock(Src);
537 if (isa<UndefValue>(Val)) continue;
544 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
545 const BasicBlock* TrueBB,
546 const BasicBlock* FalseBB) {
547 if (TrueBB==FalseBB) {
548 // "TrueBB" and "FalseBB" destination equals
549 printPHICopy(CurrBB,TrueBB);
550 printSimpleInstruction("pop");
551 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
552 } else if (FalseBB==NULL) {
553 // If "FalseBB" not used the jump have condition
554 printPHICopy(CurrBB,TrueBB);
555 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
556 } else if (TrueBB==NULL) {
557 // If "TrueBB" not used the jump is unconditional
558 printPHICopy(CurrBB,FalseBB);
559 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
561 // Copy PHI instructions for each block
562 std::string TmpLabel;
563 // Print PHI instructions for "TrueBB"
564 if (isa<PHINode>(TrueBB->begin())) {
565 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
566 printSimpleInstruction("brtrue",TmpLabel.c_str());
568 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
570 // Print PHI instructions for "FalseBB"
571 if (isa<PHINode>(FalseBB->begin())) {
572 printPHICopy(CurrBB,FalseBB);
573 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
575 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
577 if (isa<PHINode>(TrueBB->begin())) {
578 // Handle "TrueBB" PHI Copy
579 Out << TmpLabel << ":\n";
580 printPHICopy(CurrBB,TrueBB);
581 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
587 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
588 if (Inst->isUnconditional()) {
589 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
591 printValueLoad(Inst->getCondition());
592 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
593 Inst->getSuccessor(1));
598 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
599 const Value* VFalse) {
600 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
601 printValueLoad(VTrue);
602 printValueLoad(Cond);
603 printSimpleInstruction("brtrue",TmpLabel.c_str());
604 printSimpleInstruction("pop");
605 printValueLoad(VFalse);
606 Out << TmpLabel << ":\n";
610 void MSILWriter::printIndirectLoad(const Value* V) {
611 const Type* Ty = V->getType();
613 if (const PointerType* P = dyn_cast<PointerType>(Ty))
614 Ty = P->getElementType();
615 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
616 printSimpleInstruction(Tmp.c_str());
620 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
623 printIndirectSave(Val->getType());
627 void MSILWriter::printIndirectSave(const Type* Ty) {
628 // Instruction need signed postfix for any type.
629 std::string postfix = getTypePostfix(Ty, false);
630 if (*postfix.begin()=='u') *postfix.begin() = 'i';
631 postfix = "stind."+postfix;
632 printSimpleInstruction(postfix.c_str());
636 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
642 case Instruction::SExt:
643 case Instruction::SIToFP:
644 case Instruction::FPToSI:
645 Tmp = "conv."+getTypePostfix(Ty,false,true);
646 printSimpleInstruction(Tmp.c_str());
649 case Instruction::FPTrunc:
650 case Instruction::FPExt:
651 case Instruction::UIToFP:
652 case Instruction::Trunc:
653 case Instruction::ZExt:
654 case Instruction::FPToUI:
655 case Instruction::PtrToInt:
656 case Instruction::IntToPtr:
657 Tmp = "conv."+getTypePostfix(Ty,false);
658 printSimpleInstruction(Tmp.c_str());
661 case Instruction::BitCast:
662 // FIXME: meaning that ld*/st* instruction do not change data format.
665 cerr << "Opcode = " << Op << '\n';
666 assert(0 && "Invalid conversion instruction");
671 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
672 gep_type_iterator E) {
675 printValuePtrLoad(V);
676 // Calculate element offset.
679 const Value* IndexValue = I.getOperand();
680 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
681 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
682 // Offset is the sum of all previous structure fields.
683 for (uint64_t F = 0; F<FieldIndex; ++F)
684 Size += TD->getABITypeSize(StrucTy->getContainedType((unsigned)F));
686 printSimpleInstruction("add");
688 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
689 Size = TD->getABITypeSize(SeqTy->getElementType());
691 Size = TD->getABITypeSize(*I);
693 // Add offset of current element to stack top.
694 if (!isZeroValue(IndexValue)) {
695 // Constant optimization.
696 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
697 if (C->getValue().isNegative()) {
698 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
699 printSimpleInstruction("sub");
702 printPtrLoad(C->getZExtValue()*Size);
705 printValuePtrLoad(IndexValue);
706 printSimpleInstruction("mul");
708 printSimpleInstruction("add");
714 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
715 const Instruction* Inst,
718 if (Ty->isVarArg()) Tmp += "vararg ";
719 // Name and return type.
720 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
721 // Function argument type list.
722 unsigned NumParams = Ty->getNumParams();
723 for (unsigned I = 0; I!=NumParams; ++I) {
724 if (I!=0) Tmp += ",";
725 Tmp += getTypeName(Ty->getParamType(I));
727 // CLR needs to know the exact amount of parameters received by vararg
728 // function, because caller cleans the stack.
729 if (Ty->isVarArg() && Inst) {
730 // Origin to function arguments in "CallInst" or "InvokeInst".
731 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
732 // Print variable argument types.
733 unsigned NumOperands = Inst->getNumOperands()-Org;
734 if (NumParams<NumOperands) {
735 if (NumParams!=0) Tmp += ", ";
737 for (unsigned J = NumParams; J!=NumOperands; ++J) {
738 if (J!=NumParams) Tmp += ", ";
739 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
747 void MSILWriter::printFunctionCall(const Value* FnVal,
748 const Instruction* Inst) {
749 // Get function calling convention.
750 std::string Name = "";
751 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
752 Name = getConvModopt(Call->getCallingConv());
753 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
754 Name = getConvModopt(Invoke->getCallingConv());
756 cerr << "Instruction = " << Inst->getName() << '\n';
757 assert(0 && "Need \"Invoke\" or \"Call\" instruction only");
759 if (const Function* F = dyn_cast<Function>(FnVal)) {
761 Name += getValueName(F);
762 printSimpleInstruction("call",
763 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
765 // Indirect function call.
766 const PointerType* PTy = cast<PointerType>(FnVal->getType());
767 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
768 // Load function address.
769 printValueLoad(FnVal);
770 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
775 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
777 switch (Inst->getIntrinsicID()) {
778 case Intrinsic::vastart:
779 Name = getValueName(Inst->getOperand(1));
780 Name.insert(Name.length()-1,"$valist");
781 // Obtain the argument handle.
782 printSimpleInstruction("ldloca",Name.c_str());
783 printSimpleInstruction("arglist");
784 printSimpleInstruction("call",
785 "instance void [mscorlib]System.ArgIterator::.ctor"
786 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
787 // Save as pointer type "void*"
788 printValueLoad(Inst->getOperand(1));
789 printSimpleInstruction("ldloca",Name.c_str());
790 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
792 case Intrinsic::vaend:
793 // Close argument list handle.
794 printIndirectLoad(Inst->getOperand(1));
795 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
797 case Intrinsic::vacopy:
798 // Copy "ArgIterator" valuetype.
799 printIndirectLoad(Inst->getOperand(1));
800 printIndirectLoad(Inst->getOperand(2));
801 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
804 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
805 assert(0 && "Invalid intrinsic function");
810 void MSILWriter::printCallInstruction(const Instruction* Inst) {
811 if (isa<IntrinsicInst>(Inst)) {
812 // Handle intrinsic function.
813 printIntrinsicCall(cast<IntrinsicInst>(Inst));
815 // Load arguments to stack and call function.
816 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
817 printValueLoad(Inst->getOperand(I));
818 printFunctionCall(Inst->getOperand(0),Inst);
823 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
824 const Value* Right) {
826 case ICmpInst::ICMP_EQ:
827 printBinaryInstruction("ceq",Left,Right);
829 case ICmpInst::ICMP_NE:
830 // Emulate = not neg (Op1 eq Op2)
831 printBinaryInstruction("ceq",Left,Right);
832 printSimpleInstruction("neg");
833 printSimpleInstruction("not");
835 case ICmpInst::ICMP_ULE:
836 case ICmpInst::ICMP_SLE:
837 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
838 printBinaryInstruction("ceq",Left,Right);
839 if (Predicate==ICmpInst::ICMP_ULE)
840 printBinaryInstruction("clt.un",Left,Right);
842 printBinaryInstruction("clt",Left,Right);
843 printSimpleInstruction("or");
845 case ICmpInst::ICMP_UGE:
846 case ICmpInst::ICMP_SGE:
847 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
848 printBinaryInstruction("ceq",Left,Right);
849 if (Predicate==ICmpInst::ICMP_UGE)
850 printBinaryInstruction("cgt.un",Left,Right);
852 printBinaryInstruction("cgt",Left,Right);
853 printSimpleInstruction("or");
855 case ICmpInst::ICMP_ULT:
856 printBinaryInstruction("clt.un",Left,Right);
858 case ICmpInst::ICMP_SLT:
859 printBinaryInstruction("clt",Left,Right);
861 case ICmpInst::ICMP_UGT:
862 printBinaryInstruction("cgt.un",Left,Right);
863 case ICmpInst::ICMP_SGT:
864 printBinaryInstruction("cgt",Left,Right);
867 cerr << "Predicate = " << Predicate << '\n';
868 assert(0 && "Invalid icmp predicate");
873 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
874 const Value* Right) {
875 // FIXME: Correct comparison
876 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
878 case FCmpInst::FCMP_UGT:
879 // X > Y || llvm_fcmp_uno(X, Y)
880 printBinaryInstruction("cgt",Left,Right);
881 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
882 printSimpleInstruction("or");
884 case FCmpInst::FCMP_OGT:
886 printBinaryInstruction("cgt",Left,Right);
888 case FCmpInst::FCMP_UGE:
889 // X >= Y || llvm_fcmp_uno(X, Y)
890 printBinaryInstruction("ceq",Left,Right);
891 printBinaryInstruction("cgt",Left,Right);
892 printSimpleInstruction("or");
893 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
894 printSimpleInstruction("or");
896 case FCmpInst::FCMP_OGE:
898 printBinaryInstruction("ceq",Left,Right);
899 printBinaryInstruction("cgt",Left,Right);
900 printSimpleInstruction("or");
902 case FCmpInst::FCMP_ULT:
903 // X < Y || llvm_fcmp_uno(X, Y)
904 printBinaryInstruction("clt",Left,Right);
905 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
906 printSimpleInstruction("or");
908 case FCmpInst::FCMP_OLT:
910 printBinaryInstruction("clt",Left,Right);
912 case FCmpInst::FCMP_ULE:
913 // X <= Y || llvm_fcmp_uno(X, Y)
914 printBinaryInstruction("ceq",Left,Right);
915 printBinaryInstruction("clt",Left,Right);
916 printSimpleInstruction("or");
917 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
918 printSimpleInstruction("or");
920 case FCmpInst::FCMP_OLE:
922 printBinaryInstruction("ceq",Left,Right);
923 printBinaryInstruction("clt",Left,Right);
924 printSimpleInstruction("or");
926 case FCmpInst::FCMP_UEQ:
927 // X == Y || llvm_fcmp_uno(X, Y)
928 printBinaryInstruction("ceq",Left,Right);
929 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
930 printSimpleInstruction("or");
932 case FCmpInst::FCMP_OEQ:
934 printBinaryInstruction("ceq",Left,Right);
936 case FCmpInst::FCMP_UNE:
938 printBinaryInstruction("ceq",Left,Right);
939 printSimpleInstruction("neg");
940 printSimpleInstruction("not");
942 case FCmpInst::FCMP_ONE:
943 // X != Y && llvm_fcmp_ord(X, Y)
944 printBinaryInstruction("ceq",Left,Right);
945 printSimpleInstruction("not");
947 case FCmpInst::FCMP_ORD:
948 // return X == X && Y == Y
949 printBinaryInstruction("ceq",Left,Left);
950 printBinaryInstruction("ceq",Right,Right);
951 printSimpleInstruction("or");
953 case FCmpInst::FCMP_UNO:
955 printBinaryInstruction("ceq",Left,Left);
956 printSimpleInstruction("not");
957 printBinaryInstruction("ceq",Right,Right);
958 printSimpleInstruction("not");
959 printSimpleInstruction("or");
962 assert(0 && "Illegal FCmp predicate");
967 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
968 std::string Label = "leave$normal_"+utostr(getUniqID());
971 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
972 printValueLoad(Inst->getOperand(I));
973 // Print call instruction
974 printFunctionCall(Inst->getOperand(0),Inst);
975 // Save function result and leave "try" block
976 printValueSave(Inst);
977 printSimpleInstruction("leave",Label.c_str());
979 Out << "catch [mscorlib]System.Exception {\n";
980 // Redirect to unwind block
981 printSimpleInstruction("pop");
982 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
983 Out << "}\n" << Label << ":\n";
984 // Redirect to continue block
985 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
989 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
990 // FIXME: Emulate with IL "switch" instruction
991 // Emulate = if () else if () else if () else ...
992 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
993 printValueLoad(Inst->getCondition());
994 printValueLoad(Inst->getCaseValue(I));
995 printSimpleInstruction("ceq");
996 // Condition jump to successor block
997 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
999 // Jump to default block
1000 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1004 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1005 printIndirectLoad(Inst->getOperand(0));
1006 printSimpleInstruction("call",
1007 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1008 printSimpleInstruction("refanyval","void*");
1010 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1011 printSimpleInstruction(Name.c_str());
1015 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1016 uint64_t Size = TD->getABITypeSize(Inst->getAllocatedType());
1017 // Constant optimization.
1018 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1019 printPtrLoad(CInt->getZExtValue()*Size);
1022 printValueLoad(Inst->getOperand(0));
1023 printSimpleInstruction("mul");
1025 printSimpleInstruction("localloc");
1029 void MSILWriter::printInstruction(const Instruction* Inst) {
1030 const Value *Left = 0, *Right = 0;
1031 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1032 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1033 // Print instruction
1034 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1035 switch (Inst->getOpcode()) {
1037 case Instruction::Ret:
1038 if (Inst->getNumOperands()) {
1039 printValueLoad(Left);
1040 printSimpleInstruction("ret");
1042 printSimpleInstruction("ret");
1044 case Instruction::Br:
1045 printBranchInstruction(cast<BranchInst>(Inst));
1048 case Instruction::Add:
1049 printBinaryInstruction("add",Left,Right);
1051 case Instruction::Sub:
1052 printBinaryInstruction("sub",Left,Right);
1054 case Instruction::Mul:
1055 printBinaryInstruction("mul",Left,Right);
1057 case Instruction::UDiv:
1058 printBinaryInstruction("div.un",Left,Right);
1060 case Instruction::SDiv:
1061 case Instruction::FDiv:
1062 printBinaryInstruction("div",Left,Right);
1064 case Instruction::URem:
1065 printBinaryInstruction("rem.un",Left,Right);
1067 case Instruction::SRem:
1068 case Instruction::FRem:
1069 printBinaryInstruction("rem",Left,Right);
1072 case Instruction::ICmp:
1073 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1075 case Instruction::FCmp:
1076 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1079 case Instruction::And:
1080 printBinaryInstruction("and",Left,Right);
1082 case Instruction::Or:
1083 printBinaryInstruction("or",Left,Right);
1085 case Instruction::Xor:
1086 printBinaryInstruction("xor",Left,Right);
1088 case Instruction::Shl:
1089 printValueLoad(Left);
1090 printValueLoad(Right);
1091 printSimpleInstruction("conv.i4");
1092 printSimpleInstruction("shl");
1094 case Instruction::LShr:
1095 printValueLoad(Left);
1096 printValueLoad(Right);
1097 printSimpleInstruction("conv.i4");
1098 printSimpleInstruction("shr.un");
1100 case Instruction::AShr:
1101 printValueLoad(Left);
1102 printValueLoad(Right);
1103 printSimpleInstruction("conv.i4");
1104 printSimpleInstruction("shr");
1106 case Instruction::Select:
1107 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1109 case Instruction::Load:
1110 printIndirectLoad(Inst->getOperand(0));
1112 case Instruction::Store:
1113 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1115 case Instruction::Trunc:
1116 case Instruction::ZExt:
1117 case Instruction::SExt:
1118 case Instruction::FPTrunc:
1119 case Instruction::FPExt:
1120 case Instruction::UIToFP:
1121 case Instruction::SIToFP:
1122 case Instruction::FPToUI:
1123 case Instruction::FPToSI:
1124 case Instruction::PtrToInt:
1125 case Instruction::IntToPtr:
1126 case Instruction::BitCast:
1127 printCastInstruction(Inst->getOpcode(),Left,
1128 cast<CastInst>(Inst)->getDestTy());
1130 case Instruction::GetElementPtr:
1131 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1132 gep_type_end(Inst));
1134 case Instruction::Call:
1135 printCallInstruction(cast<CallInst>(Inst));
1137 case Instruction::Invoke:
1138 printInvokeInstruction(cast<InvokeInst>(Inst));
1140 case Instruction::Unwind:
1141 printSimpleInstruction("newobj",
1142 "instance void [mscorlib]System.Exception::.ctor()");
1143 printSimpleInstruction("throw");
1145 case Instruction::Switch:
1146 printSwitchInstruction(cast<SwitchInst>(Inst));
1148 case Instruction::Alloca:
1149 printAllocaInstruction(cast<AllocaInst>(Inst));
1151 case Instruction::Malloc:
1152 assert(0 && "LowerAllocationsPass used");
1154 case Instruction::Free:
1155 assert(0 && "LowerAllocationsPass used");
1157 case Instruction::Unreachable:
1158 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1159 printSimpleInstruction("newobj",
1160 "instance void [mscorlib]System.Exception::.ctor(string)");
1161 printSimpleInstruction("throw");
1163 case Instruction::VAArg:
1164 printVAArgInstruction(cast<VAArgInst>(Inst));
1167 cerr << "Instruction = " << Inst->getName() << '\n';
1168 assert(0 && "Unsupported instruction");
1173 void MSILWriter::printLoop(const Loop* L) {
1174 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1175 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1176 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1177 BasicBlock* BB = blocks[I];
1178 Loop* BBLoop = LInfo->getLoopFor(BB);
1180 printBasicBlock(BB);
1181 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1184 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1188 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1189 Out << getLabelName(BB) << ":\n";
1190 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1191 const Instruction* Inst = I;
1192 // Comment llvm original instruction
1193 // Out << "\n//" << *Inst << "\n";
1194 // Do not handle PHI instruction in current block
1195 if (Inst->getOpcode()==Instruction::PHI) continue;
1196 // Print instruction
1197 printInstruction(Inst);
1199 if (Inst->getType()!=Type::VoidTy) {
1200 // Do not save value after invoke, it done in "try" block
1201 if (Inst->getOpcode()==Instruction::Invoke) continue;
1202 printValueSave(Inst);
1208 void MSILWriter::printLocalVariables(const Function& F) {
1210 const Type* Ty = NULL;
1211 std::set<const Value*> Printed;
1212 const Value* VaList = NULL;
1213 unsigned StackDepth = 8;
1214 // Find local variables
1215 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1216 if (I->getOpcode()==Instruction::Call ||
1217 I->getOpcode()==Instruction::Invoke) {
1218 // Test stack depth.
1219 if (StackDepth<I->getNumOperands())
1220 StackDepth = I->getNumOperands();
1222 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1223 if (AI && !isa<GlobalVariable>(AI)) {
1224 // Local variable allocation.
1225 Ty = PointerType::getUnqual(AI->getAllocatedType());
1226 Name = getValueName(AI);
1227 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1228 } else if (I->getType()!=Type::VoidTy) {
1229 // Operation result.
1231 Name = getValueName(&*I);
1232 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1234 // Test on 'va_list' variable
1235 bool isVaList = false;
1236 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1237 // "va_list" as "va_arg" instruction operand.
1239 VaList = VaInst->getOperand(0);
1240 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1241 // "va_list" as intrinsic function operand.
1242 switch (Inst->getIntrinsicID()) {
1243 case Intrinsic::vastart:
1244 case Intrinsic::vaend:
1245 case Intrinsic::vacopy:
1247 VaList = Inst->getOperand(1);
1253 // Print "va_list" variable.
1254 if (isVaList && Printed.insert(VaList).second) {
1255 Name = getValueName(VaList);
1256 Name.insert(Name.length()-1,"$valist");
1257 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1261 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1265 void MSILWriter::printFunctionBody(const Function& F) {
1267 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1268 if (Loop *L = LInfo->getLoopFor(I)) {
1269 if (L->getHeader()==I && L->getParentLoop()==0)
1278 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1279 const Value *left = 0, *right = 0;
1280 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1281 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1282 // Print instruction
1283 switch (CE->getOpcode()) {
1284 case Instruction::Trunc:
1285 case Instruction::ZExt:
1286 case Instruction::SExt:
1287 case Instruction::FPTrunc:
1288 case Instruction::FPExt:
1289 case Instruction::UIToFP:
1290 case Instruction::SIToFP:
1291 case Instruction::FPToUI:
1292 case Instruction::FPToSI:
1293 case Instruction::PtrToInt:
1294 case Instruction::IntToPtr:
1295 case Instruction::BitCast:
1296 printCastInstruction(CE->getOpcode(),left,CE->getType());
1298 case Instruction::GetElementPtr:
1299 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1301 case Instruction::ICmp:
1302 printICmpInstruction(CE->getPredicate(),left,right);
1304 case Instruction::FCmp:
1305 printFCmpInstruction(CE->getPredicate(),left,right);
1307 case Instruction::Select:
1308 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1310 case Instruction::Add:
1311 printBinaryInstruction("add",left,right);
1313 case Instruction::Sub:
1314 printBinaryInstruction("sub",left,right);
1316 case Instruction::Mul:
1317 printBinaryInstruction("mul",left,right);
1319 case Instruction::UDiv:
1320 printBinaryInstruction("div.un",left,right);
1322 case Instruction::SDiv:
1323 case Instruction::FDiv:
1324 printBinaryInstruction("div",left,right);
1326 case Instruction::URem:
1327 printBinaryInstruction("rem.un",left,right);
1329 case Instruction::SRem:
1330 case Instruction::FRem:
1331 printBinaryInstruction("rem",left,right);
1333 case Instruction::And:
1334 printBinaryInstruction("and",left,right);
1336 case Instruction::Or:
1337 printBinaryInstruction("or",left,right);
1339 case Instruction::Xor:
1340 printBinaryInstruction("xor",left,right);
1342 case Instruction::Shl:
1343 printBinaryInstruction("shl",left,right);
1345 case Instruction::LShr:
1346 printBinaryInstruction("shr.un",left,right);
1348 case Instruction::AShr:
1349 printBinaryInstruction("shr",left,right);
1352 cerr << "Expression = " << *CE << "\n";
1353 assert(0 && "Invalid constant expression");
1358 void MSILWriter::printStaticInitializerList() {
1359 // List of global variables with uninitialized fields.
1360 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1361 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1363 const std::vector<StaticInitializer>& InitList = VarI->second;
1364 if (InitList.empty()) continue;
1365 // For each uninitialized field.
1366 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1367 E = InitList.end(); I!=E; ++I) {
1368 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1369 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1370 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1371 // Load variable address
1372 printValueLoad(VarI->first);
1375 printPtrLoad(I->offset);
1376 printSimpleInstruction("add");
1379 printConstantExpr(CE);
1380 // Save result at offset
1381 std::string postfix = getTypePostfix(CE->getType(),true);
1382 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1383 postfix = "stind."+postfix;
1384 printSimpleInstruction(postfix.c_str());
1386 cerr << "Constant = " << *I->constant << '\n';
1387 assert(0 && "Invalid static initializer");
1394 void MSILWriter::printFunction(const Function& F) {
1395 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1396 Out << "\n.method static ";
1397 Out << (F.hasInternalLinkage() ? "private " : "public ");
1398 if (F.isVarArg()) Out << "vararg ";
1399 Out << getTypeName(F.getReturnType(),isSigned) <<
1400 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1403 unsigned ArgIdx = 1;
1404 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1406 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1407 if (I!=F.arg_begin()) Out << ", ";
1408 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1410 Out << ") cil managed\n";
1413 printLocalVariables(F);
1414 printFunctionBody(F);
1419 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1421 std::set<const Type*> Printed;
1422 for (std::set<const Type*>::const_iterator
1423 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1424 const Type* Ty = *UI;
1425 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1426 Name = getTypeName(Ty, false, true);
1427 // Type with no need to declare.
1429 // Print not duplicated type
1430 if (Printed.insert(Ty).second) {
1431 Out << ".class value explicit ansi sealed '" << Name << "'";
1432 Out << " { .pack " << 1 << " .size " << TD->getABITypeSize(Ty)<< " }\n\n";
1438 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1439 unsigned int N = Ty->getPrimitiveSizeInBits();
1440 assert(N!=0 && "Invalid type in getBitWidth()");
1449 cerr << "Bits = " << N << '\n';
1450 assert(0 && "Unsupported integer width");
1452 return 0; // Not reached
1456 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1457 uint64_t TySize = 0;
1458 const Type* Ty = C->getType();
1459 // Print zero initialized constant.
1460 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1461 TySize = TD->getABITypeSize(C->getType());
1463 Out << "int8 (0) [" << TySize << "]";
1466 // Print constant initializer
1467 switch (Ty->getTypeID()) {
1468 case Type::IntegerTyID: {
1469 TySize = TD->getABITypeSize(Ty);
1470 const ConstantInt* Int = cast<ConstantInt>(C);
1471 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1474 case Type::FloatTyID:
1475 case Type::DoubleTyID: {
1476 TySize = TD->getABITypeSize(Ty);
1477 const ConstantFP* FP = cast<ConstantFP>(C);
1478 if (Ty->getTypeID() == Type::FloatTyID)
1480 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1483 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1486 case Type::ArrayTyID:
1487 case Type::VectorTyID:
1488 case Type::StructTyID:
1489 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1490 if (I!=0) Out << ",\n";
1491 printStaticConstant(C->getOperand(I),Offset);
1494 case Type::PointerTyID:
1495 TySize = TD->getABITypeSize(C->getType());
1496 // Initialize with global variable address
1497 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1498 std::string name = getValueName(G);
1499 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1501 // Dynamic initialization
1502 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1503 InitListPtr->push_back(StaticInitializer(C,Offset));
1504 // Null pointer initialization
1505 if (TySize==4) Out << "int32 (0)";
1506 else if (TySize==8) Out << "int64 (0)";
1507 else assert(0 && "Invalid pointer size");
1511 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1512 assert(0 && "Invalid type in printStaticConstant()");
1519 void MSILWriter::printStaticInitializer(const Constant* C,
1520 const std::string& Name) {
1521 switch (C->getType()->getTypeID()) {
1522 case Type::IntegerTyID:
1523 case Type::FloatTyID:
1524 case Type::DoubleTyID:
1525 Out << getPrimitiveTypeName(C->getType(), false);
1527 case Type::ArrayTyID:
1528 case Type::VectorTyID:
1529 case Type::StructTyID:
1530 case Type::PointerTyID:
1531 Out << getTypeName(C->getType());
1534 cerr << "Type = " << *C << "\n";
1535 assert(0 && "Invalid constant type");
1537 // Print initializer
1538 std::string label = Name;
1539 label.insert(label.length()-1,"$data");
1540 Out << Name << " at " << label << '\n';
1541 Out << ".data " << label << " = {\n";
1542 uint64_t offset = 0;
1543 printStaticConstant(C,offset);
1548 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1549 const Constant* C = G->getInitializer();
1550 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1553 InitListPtr = &StaticInitList[G];
1554 printStaticInitializer(C,getValueName(G));
1558 void MSILWriter::printGlobalVariables() {
1559 if (ModulePtr->global_empty()) return;
1560 Module::global_iterator I,E;
1561 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1562 // Variable definition
1563 Out << ".field static " << (I->isDeclaration() ? "public " :
1565 if (I->isDeclaration()) {
1566 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1568 printVariableDefinition(&*I);
1573 const char* MSILWriter::getLibraryName(const Function* F) {
1574 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1578 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1579 return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1583 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1584 unsigned CallingConv) {
1585 // TODO: Read *.def file with function and libraries definitions.
1586 return "MSVCRT.DLL";
1590 void MSILWriter::printExternals() {
1591 Module::const_iterator I,E;
1593 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1595 if (I->isIntrinsic()) continue;
1596 if (I->isDeclaration()) {
1597 const Function* F = I;
1598 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1600 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1601 Out << ".method static hidebysig pinvokeimpl(\""
1602 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1605 // External variables and static initialization.
1607 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1608 " native int LoadLibrary(string) preservesig {}\n"
1609 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1610 " native int GetProcAddress(native int, string) preservesig {}\n";
1612 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1615 "\tcall\tnative int LoadLibrary(string)\n"
1617 "\tcall\tnative int GetProcAddress(native int,string)\n"
1620 "\tldstr\t\"Can no import variable\"\n"
1621 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1626 ".method static private void $MSIL_Init() managed cil\n{\n";
1627 printStaticInitializerList();
1628 // Foreach global variable.
1629 for (Module::global_iterator I = ModulePtr->global_begin(),
1630 E = ModulePtr->global_end(); I!=E; ++I) {
1631 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1632 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1633 std::string Label = "not_null$_"+utostr(getUniqID());
1634 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1635 printSimpleInstruction("ldsflda",Tmp.c_str());
1636 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1637 Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1638 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1639 printIndirectSave(I->getType());
1641 printSimpleInstruction("ret");
1646 //===----------------------------------------------------------------------===//
1647 // External Interface declaration
1648 //===----------------------------------------------------------------------===//
1650 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
1651 CodeGenFileType FileType, bool Fast)
1653 if (FileType != TargetMachine::AssemblyFile) return true;
1654 MSILWriter* Writer = new MSILWriter(o);
1655 PM.add(createGCLoweringPass());
1656 PM.add(createLowerAllocationsPass(true));
1657 // FIXME: Handle switch trougth native IL instruction "switch"
1658 PM.add(createLowerSwitchPass());
1659 PM.add(createCFGSimplificationPass());
1660 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1662 PM.add(createGCInfoDeleter());