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; }
47 /// MSILTargetMachineModule - Note that this is used on hosts that
48 /// cannot link in a library unless there are references into the
49 /// library. In particular, it seems that it is not possible to get
50 /// things to work on Win32 without this. Though it is unused, do not
52 extern "C" int MSILTargetMachineModule;
53 int MSILTargetMachineModule = 0;
55 static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
57 bool MSILModule::runOnModule(Module &M) {
59 TD = &getAnalysis<TargetData>();
62 TypeSymbolTable& Table = M.getTypeSymbolTable();
63 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
64 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
65 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
68 std::set<const Type *>::iterator T = Types.find(I->second);
77 // Find unnamed types.
78 unsigned RenameCounter = 0;
79 for (std::set<const Type *>::const_iterator I = Types.begin(),
80 E = Types.end(); I!=E; ++I)
81 if (const StructType *STy = dyn_cast<StructType>(*I)) {
82 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
86 // Pointer for FunctionPass.
87 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
91 char MSILModule::ID = 0;
92 char MSILWriter::ID = 0;
94 bool MSILWriter::runOnFunction(Function &F) {
95 if (F.isDeclaration()) return false;
96 LInfo = &getAnalysis<LoopInfo>();
102 bool MSILWriter::doInitialization(Module &M) {
104 Mang = new Mangler(M);
105 Out << ".assembly extern mscorlib {}\n";
106 Out << ".assembly MSIL {}\n\n";
107 Out << "// External\n";
109 Out << "// Declarations\n";
110 printDeclarations(M.getTypeSymbolTable());
111 Out << "// Definitions\n";
112 printGlobalVariables();
113 Out << "// Startup code\n";
114 printModuleStartup();
119 bool MSILWriter::doFinalization(Module &M) {
125 void MSILWriter::printModuleStartup() {
127 ".method static public int32 $MSIL_Startup() {\n"
129 "\t.locals (native int i)\n"
130 "\t.locals (native int argc)\n"
131 "\t.locals (native int ptr)\n"
132 "\t.locals (void* argv)\n"
133 "\t.locals (string[] args)\n"
134 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
141 printPtrLoad(TD->getPointerSize());
156 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
157 "StringToHGlobalAnsi(string)\n"
161 printPtrLoad(TD->getPointerSize());
173 "\tcall void $MSIL_Init()\n";
175 // Call user 'main' function.
176 const Function* F = ModulePtr->getFunction("main");
177 if (!F || F->isDeclaration()) {
178 Out << "\tldc.i4.0\n\tret\n}\n";
182 std::string Args("");
183 Function::const_arg_iterator Arg1,Arg2;
185 switch (F->arg_size()) {
190 Arg1 = F->arg_begin();
191 if (Arg1->getType()->isInteger()) {
192 Out << "\tldloc\targc\n";
193 Args = getTypeName(Arg1->getType());
198 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
199 if (Arg1->getType()->isInteger() &&
200 Arg2->getType()->getTypeID() == Type::PointerTyID) {
201 Out << "\tldloc\targc\n\tldloc\targv\n";
202 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
210 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
211 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
212 Out << "\tldc.i4.0\n";
214 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
215 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
217 Out << "\tldc.i4.0\n";
219 Out << "\tconv.i4\n";
224 bool MSILWriter::isZeroValue(const Value* V) {
225 if (const Constant *C = dyn_cast<Constant>(V))
226 return C->isNullValue();
231 std::string MSILWriter::getValueName(const Value* V) {
232 // Name into the quotes allow control and space characters.
233 return "'"+Mang->getValueName(V)+"'";
237 std::string MSILWriter::getLabelName(const std::string& Name) {
238 if (Name.find('.')!=std::string::npos) {
239 std::string Tmp(Name);
240 // Replace unaccepable characters in the label name.
241 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
242 if (*I=='.') *I = '@';
249 std::string MSILWriter::getLabelName(const Value* V) {
250 return getLabelName(Mang->getValueName(V));
254 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
255 switch (CallingConvID) {
257 case CallingConv::Cold:
258 case CallingConv::Fast:
259 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
260 case CallingConv::X86_FastCall:
261 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
262 case CallingConv::X86_StdCall:
263 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
265 cerr << "CallingConvID = " << CallingConvID << '\n';
266 assert(0 && "Unsupported calling convention");
268 return ""; // Not reached
272 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
273 std::string Tmp = "";
274 const Type* ElemTy = Ty;
275 assert(Ty->getTypeID()==TyID && "Invalid type passed");
276 // Walk trought array element types.
278 // Multidimensional array.
279 if (ElemTy->getTypeID()==TyID) {
280 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
281 Tmp += utostr(ATy->getNumElements());
282 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
283 Tmp += utostr(VTy->getNumElements());
284 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
286 // Base element type found.
287 if (ElemTy->getTypeID()!=TyID) break;
290 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
294 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
295 unsigned NumBits = 0;
296 switch (Ty->getTypeID()) {
299 case Type::IntegerTyID:
300 NumBits = getBitWidth(Ty);
304 return "unsigned int"+utostr(NumBits)+" ";
305 return "int"+utostr(NumBits)+" ";
306 case Type::FloatTyID:
308 case Type::DoubleTyID:
311 cerr << "Type = " << *Ty << '\n';
312 assert(0 && "Invalid primitive type");
314 return ""; // Not reached
318 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
320 if (Ty->isPrimitiveType() || Ty->isInteger())
321 return getPrimitiveTypeName(Ty,isSigned);
322 // FIXME: "OpaqueType" support
323 switch (Ty->getTypeID()) {
324 case Type::PointerTyID:
326 case Type::StructTyID:
328 return ModulePtr->getTypeName(Ty);
329 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
330 case Type::ArrayTyID:
332 return getArrayTypeName(Ty->getTypeID(),Ty);
333 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
334 case Type::VectorTyID:
336 return getArrayTypeName(Ty->getTypeID(),Ty);
337 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
339 cerr << "Type = " << *Ty << '\n';
340 assert(0 && "Invalid type in getTypeName()");
342 return ""; // Not reached
346 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
348 if (isa<Argument>(V))
351 else if (const Function* F = dyn_cast<Function>(V))
352 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
354 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
355 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
357 else if (isa<Constant>(V))
358 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
364 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
366 unsigned NumBits = 0;
367 switch (Ty->getTypeID()) {
368 // Integer constant, expanding for stack operations.
369 case Type::IntegerTyID:
370 NumBits = getBitWidth(Ty);
371 // Expand integer value to "int32" or "int64".
372 if (Expand) return (NumBits<=32 ? "i4" : "i8");
373 if (NumBits==1) return "i1";
374 return (isSigned ? "i" : "u")+utostr(NumBits/8);
376 case Type::FloatTyID:
378 case Type::DoubleTyID:
380 case Type::PointerTyID:
381 return "i"+utostr(TD->getTypePaddedSize(Ty));
383 cerr << "TypeID = " << Ty->getTypeID() << '\n';
384 assert(0 && "Invalid type in TypeToPostfix()");
386 return ""; // Not reached
390 void MSILWriter::printConvToPtr() {
391 switch (ModulePtr->getPointerSize()) {
392 case Module::Pointer32:
393 printSimpleInstruction("conv.u4");
395 case Module::Pointer64:
396 printSimpleInstruction("conv.u8");
399 assert(0 && "Module use not supporting pointer size");
404 void MSILWriter::printPtrLoad(uint64_t N) {
405 switch (ModulePtr->getPointerSize()) {
406 case Module::Pointer32:
407 printSimpleInstruction("ldc.i4",utostr(N).c_str());
408 // FIXME: Need overflow test?
410 cerr << "Value = " << utostr(N) << '\n';
411 assert(0 && "32-bit pointer overflowed");
414 case Module::Pointer64:
415 printSimpleInstruction("ldc.i8",utostr(N).c_str());
418 assert(0 && "Module use not supporting pointer size");
423 void MSILWriter::printValuePtrLoad(const Value* V) {
429 void MSILWriter::printConstLoad(const Constant* C) {
430 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
432 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
433 if (CInt->isMinValue(true))
434 Out << CInt->getSExtValue();
436 Out << CInt->getZExtValue();
437 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
441 if (FP->getType()->getTypeID()==Type::FloatTyID) {
442 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
445 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
448 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
449 } else if (isa<UndefValue>(C)) {
450 // Undefined constant value = NULL.
453 cerr << "Constant = " << *C << '\n';
454 assert(0 && "Invalid constant value");
460 void MSILWriter::printValueLoad(const Value* V) {
461 MSILWriter::ValueType Location = getValueLocation(V);
463 // Global variable or function address.
466 if (const Function* F = dyn_cast<Function>(V)) {
467 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
468 printSimpleInstruction("ldftn",
469 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
472 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
473 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
474 Tmp = "void* "+getValueName(V);
475 printSimpleInstruction("ldsfld",Tmp.c_str());
477 Tmp = getTypeName(ElemTy)+getValueName(V);
478 printSimpleInstruction("ldsflda",Tmp.c_str());
482 // Function argument.
484 printSimpleInstruction("ldarg",getValueName(V).c_str());
486 // Local function variable.
488 printSimpleInstruction("ldloc",getValueName(V).c_str());
492 if (isa<ConstantPointerNull>(V))
495 printConstLoad(cast<Constant>(V));
497 // Constant expression.
499 printConstantExpr(cast<ConstantExpr>(V));
502 cerr << "Value = " << *V << '\n';
503 assert(0 && "Invalid value location");
508 void MSILWriter::printValueSave(const Value* V) {
509 switch (getValueLocation(V)) {
511 printSimpleInstruction("starg",getValueName(V).c_str());
514 printSimpleInstruction("stloc",getValueName(V).c_str());
517 cerr << "Value = " << *V << '\n';
518 assert(0 && "Invalid value location");
523 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
524 const Value* Right) {
525 printValueLoad(Left);
526 printValueLoad(Right);
527 Out << '\t' << Name << '\n';
531 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
533 Out << '\t' << Inst << '\t' << Operand << '\n';
535 Out << '\t' << Inst << '\n';
539 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
540 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
541 isa<PHINode>(I); ++I) {
542 const PHINode* Phi = cast<PHINode>(I);
543 const Value* Val = Phi->getIncomingValueForBlock(Src);
544 if (isa<UndefValue>(Val)) continue;
551 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
552 const BasicBlock* TrueBB,
553 const BasicBlock* FalseBB) {
554 if (TrueBB==FalseBB) {
555 // "TrueBB" and "FalseBB" destination equals
556 printPHICopy(CurrBB,TrueBB);
557 printSimpleInstruction("pop");
558 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
559 } else if (FalseBB==NULL) {
560 // If "FalseBB" not used the jump have condition
561 printPHICopy(CurrBB,TrueBB);
562 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
563 } else if (TrueBB==NULL) {
564 // If "TrueBB" not used the jump is unconditional
565 printPHICopy(CurrBB,FalseBB);
566 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
568 // Copy PHI instructions for each block
569 std::string TmpLabel;
570 // Print PHI instructions for "TrueBB"
571 if (isa<PHINode>(TrueBB->begin())) {
572 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
573 printSimpleInstruction("brtrue",TmpLabel.c_str());
575 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
577 // Print PHI instructions for "FalseBB"
578 if (isa<PHINode>(FalseBB->begin())) {
579 printPHICopy(CurrBB,FalseBB);
580 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
582 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
584 if (isa<PHINode>(TrueBB->begin())) {
585 // Handle "TrueBB" PHI Copy
586 Out << TmpLabel << ":\n";
587 printPHICopy(CurrBB,TrueBB);
588 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
594 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
595 if (Inst->isUnconditional()) {
596 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
598 printValueLoad(Inst->getCondition());
599 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
600 Inst->getSuccessor(1));
605 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
606 const Value* VFalse) {
607 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
608 printValueLoad(VTrue);
609 printValueLoad(Cond);
610 printSimpleInstruction("brtrue",TmpLabel.c_str());
611 printSimpleInstruction("pop");
612 printValueLoad(VFalse);
613 Out << TmpLabel << ":\n";
617 void MSILWriter::printIndirectLoad(const Value* V) {
618 const Type* Ty = V->getType();
620 if (const PointerType* P = dyn_cast<PointerType>(Ty))
621 Ty = P->getElementType();
622 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
623 printSimpleInstruction(Tmp.c_str());
627 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
630 printIndirectSave(Val->getType());
634 void MSILWriter::printIndirectSave(const Type* Ty) {
635 // Instruction need signed postfix for any type.
636 std::string postfix = getTypePostfix(Ty, false);
637 if (*postfix.begin()=='u') *postfix.begin() = 'i';
638 postfix = "stind."+postfix;
639 printSimpleInstruction(postfix.c_str());
643 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
649 case Instruction::SExt:
650 case Instruction::SIToFP:
651 case Instruction::FPToSI:
652 Tmp = "conv."+getTypePostfix(Ty,false,true);
653 printSimpleInstruction(Tmp.c_str());
656 case Instruction::FPTrunc:
657 case Instruction::FPExt:
658 case Instruction::UIToFP:
659 case Instruction::Trunc:
660 case Instruction::ZExt:
661 case Instruction::FPToUI:
662 case Instruction::PtrToInt:
663 case Instruction::IntToPtr:
664 Tmp = "conv."+getTypePostfix(Ty,false);
665 printSimpleInstruction(Tmp.c_str());
668 case Instruction::BitCast:
669 // FIXME: meaning that ld*/st* instruction do not change data format.
672 cerr << "Opcode = " << Op << '\n';
673 assert(0 && "Invalid conversion instruction");
678 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
679 gep_type_iterator E) {
682 printValuePtrLoad(V);
683 // Calculate element offset.
686 const Value* IndexValue = I.getOperand();
687 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
688 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
689 // Offset is the sum of all previous structure fields.
690 for (uint64_t F = 0; F<FieldIndex; ++F)
691 Size += TD->getTypePaddedSize(StrucTy->getContainedType((unsigned)F));
693 printSimpleInstruction("add");
695 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
696 Size = TD->getTypePaddedSize(SeqTy->getElementType());
698 Size = TD->getTypePaddedSize(*I);
700 // Add offset of current element to stack top.
701 if (!isZeroValue(IndexValue)) {
702 // Constant optimization.
703 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
704 if (C->getValue().isNegative()) {
705 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
706 printSimpleInstruction("sub");
709 printPtrLoad(C->getZExtValue()*Size);
712 printValuePtrLoad(IndexValue);
713 printSimpleInstruction("mul");
715 printSimpleInstruction("add");
721 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
722 const Instruction* Inst,
725 if (Ty->isVarArg()) Tmp += "vararg ";
726 // Name and return type.
727 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
728 // Function argument type list.
729 unsigned NumParams = Ty->getNumParams();
730 for (unsigned I = 0; I!=NumParams; ++I) {
731 if (I!=0) Tmp += ",";
732 Tmp += getTypeName(Ty->getParamType(I));
734 // CLR needs to know the exact amount of parameters received by vararg
735 // function, because caller cleans the stack.
736 if (Ty->isVarArg() && Inst) {
737 // Origin to function arguments in "CallInst" or "InvokeInst".
738 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
739 // Print variable argument types.
740 unsigned NumOperands = Inst->getNumOperands()-Org;
741 if (NumParams<NumOperands) {
742 if (NumParams!=0) Tmp += ", ";
744 for (unsigned J = NumParams; J!=NumOperands; ++J) {
745 if (J!=NumParams) Tmp += ", ";
746 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
754 void MSILWriter::printFunctionCall(const Value* FnVal,
755 const Instruction* Inst) {
756 // Get function calling convention.
757 std::string Name = "";
758 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
759 Name = getConvModopt(Call->getCallingConv());
760 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
761 Name = getConvModopt(Invoke->getCallingConv());
763 cerr << "Instruction = " << Inst->getName() << '\n';
764 assert(0 && "Need \"Invoke\" or \"Call\" instruction only");
766 if (const Function* F = dyn_cast<Function>(FnVal)) {
768 Name += getValueName(F);
769 printSimpleInstruction("call",
770 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
772 // Indirect function call.
773 const PointerType* PTy = cast<PointerType>(FnVal->getType());
774 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
775 // Load function address.
776 printValueLoad(FnVal);
777 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
782 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
784 switch (Inst->getIntrinsicID()) {
785 case Intrinsic::vastart:
786 Name = getValueName(Inst->getOperand(1));
787 Name.insert(Name.length()-1,"$valist");
788 // Obtain the argument handle.
789 printSimpleInstruction("ldloca",Name.c_str());
790 printSimpleInstruction("arglist");
791 printSimpleInstruction("call",
792 "instance void [mscorlib]System.ArgIterator::.ctor"
793 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
794 // Save as pointer type "void*"
795 printValueLoad(Inst->getOperand(1));
796 printSimpleInstruction("ldloca",Name.c_str());
797 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
799 case Intrinsic::vaend:
800 // Close argument list handle.
801 printIndirectLoad(Inst->getOperand(1));
802 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
804 case Intrinsic::vacopy:
805 // Copy "ArgIterator" valuetype.
806 printIndirectLoad(Inst->getOperand(1));
807 printIndirectLoad(Inst->getOperand(2));
808 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
811 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
812 assert(0 && "Invalid intrinsic function");
817 void MSILWriter::printCallInstruction(const Instruction* Inst) {
818 if (isa<IntrinsicInst>(Inst)) {
819 // Handle intrinsic function.
820 printIntrinsicCall(cast<IntrinsicInst>(Inst));
822 // Load arguments to stack and call function.
823 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
824 printValueLoad(Inst->getOperand(I));
825 printFunctionCall(Inst->getOperand(0),Inst);
830 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
831 const Value* Right) {
833 case ICmpInst::ICMP_EQ:
834 printBinaryInstruction("ceq",Left,Right);
836 case ICmpInst::ICMP_NE:
837 // Emulate = not neg (Op1 eq Op2)
838 printBinaryInstruction("ceq",Left,Right);
839 printSimpleInstruction("neg");
840 printSimpleInstruction("not");
842 case ICmpInst::ICMP_ULE:
843 case ICmpInst::ICMP_SLE:
844 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
845 printBinaryInstruction("ceq",Left,Right);
846 if (Predicate==ICmpInst::ICMP_ULE)
847 printBinaryInstruction("clt.un",Left,Right);
849 printBinaryInstruction("clt",Left,Right);
850 printSimpleInstruction("or");
852 case ICmpInst::ICMP_UGE:
853 case ICmpInst::ICMP_SGE:
854 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
855 printBinaryInstruction("ceq",Left,Right);
856 if (Predicate==ICmpInst::ICMP_UGE)
857 printBinaryInstruction("cgt.un",Left,Right);
859 printBinaryInstruction("cgt",Left,Right);
860 printSimpleInstruction("or");
862 case ICmpInst::ICMP_ULT:
863 printBinaryInstruction("clt.un",Left,Right);
865 case ICmpInst::ICMP_SLT:
866 printBinaryInstruction("clt",Left,Right);
868 case ICmpInst::ICMP_UGT:
869 printBinaryInstruction("cgt.un",Left,Right);
870 case ICmpInst::ICMP_SGT:
871 printBinaryInstruction("cgt",Left,Right);
874 cerr << "Predicate = " << Predicate << '\n';
875 assert(0 && "Invalid icmp predicate");
880 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
881 const Value* Right) {
882 // FIXME: Correct comparison
883 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
885 case FCmpInst::FCMP_UGT:
886 // X > Y || llvm_fcmp_uno(X, Y)
887 printBinaryInstruction("cgt",Left,Right);
888 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
889 printSimpleInstruction("or");
891 case FCmpInst::FCMP_OGT:
893 printBinaryInstruction("cgt",Left,Right);
895 case FCmpInst::FCMP_UGE:
896 // X >= Y || llvm_fcmp_uno(X, Y)
897 printBinaryInstruction("ceq",Left,Right);
898 printBinaryInstruction("cgt",Left,Right);
899 printSimpleInstruction("or");
900 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
901 printSimpleInstruction("or");
903 case FCmpInst::FCMP_OGE:
905 printBinaryInstruction("ceq",Left,Right);
906 printBinaryInstruction("cgt",Left,Right);
907 printSimpleInstruction("or");
909 case FCmpInst::FCMP_ULT:
910 // X < Y || llvm_fcmp_uno(X, Y)
911 printBinaryInstruction("clt",Left,Right);
912 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
913 printSimpleInstruction("or");
915 case FCmpInst::FCMP_OLT:
917 printBinaryInstruction("clt",Left,Right);
919 case FCmpInst::FCMP_ULE:
920 // X <= Y || llvm_fcmp_uno(X, Y)
921 printBinaryInstruction("ceq",Left,Right);
922 printBinaryInstruction("clt",Left,Right);
923 printSimpleInstruction("or");
924 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
925 printSimpleInstruction("or");
927 case FCmpInst::FCMP_OLE:
929 printBinaryInstruction("ceq",Left,Right);
930 printBinaryInstruction("clt",Left,Right);
931 printSimpleInstruction("or");
933 case FCmpInst::FCMP_UEQ:
934 // X == Y || llvm_fcmp_uno(X, Y)
935 printBinaryInstruction("ceq",Left,Right);
936 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
937 printSimpleInstruction("or");
939 case FCmpInst::FCMP_OEQ:
941 printBinaryInstruction("ceq",Left,Right);
943 case FCmpInst::FCMP_UNE:
945 printBinaryInstruction("ceq",Left,Right);
946 printSimpleInstruction("neg");
947 printSimpleInstruction("not");
949 case FCmpInst::FCMP_ONE:
950 // X != Y && llvm_fcmp_ord(X, Y)
951 printBinaryInstruction("ceq",Left,Right);
952 printSimpleInstruction("not");
954 case FCmpInst::FCMP_ORD:
955 // return X == X && Y == Y
956 printBinaryInstruction("ceq",Left,Left);
957 printBinaryInstruction("ceq",Right,Right);
958 printSimpleInstruction("or");
960 case FCmpInst::FCMP_UNO:
962 printBinaryInstruction("ceq",Left,Left);
963 printSimpleInstruction("not");
964 printBinaryInstruction("ceq",Right,Right);
965 printSimpleInstruction("not");
966 printSimpleInstruction("or");
969 assert(0 && "Illegal FCmp predicate");
974 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
975 std::string Label = "leave$normal_"+utostr(getUniqID());
978 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
979 printValueLoad(Inst->getOperand(I));
980 // Print call instruction
981 printFunctionCall(Inst->getOperand(0),Inst);
982 // Save function result and leave "try" block
983 printValueSave(Inst);
984 printSimpleInstruction("leave",Label.c_str());
986 Out << "catch [mscorlib]System.Exception {\n";
987 // Redirect to unwind block
988 printSimpleInstruction("pop");
989 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
990 Out << "}\n" << Label << ":\n";
991 // Redirect to continue block
992 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
996 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
997 // FIXME: Emulate with IL "switch" instruction
998 // Emulate = if () else if () else if () else ...
999 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1000 printValueLoad(Inst->getCondition());
1001 printValueLoad(Inst->getCaseValue(I));
1002 printSimpleInstruction("ceq");
1003 // Condition jump to successor block
1004 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1006 // Jump to default block
1007 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1011 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1012 printIndirectLoad(Inst->getOperand(0));
1013 printSimpleInstruction("call",
1014 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1015 printSimpleInstruction("refanyval","void*");
1017 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1018 printSimpleInstruction(Name.c_str());
1022 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1023 uint64_t Size = TD->getTypePaddedSize(Inst->getAllocatedType());
1024 // Constant optimization.
1025 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1026 printPtrLoad(CInt->getZExtValue()*Size);
1029 printValueLoad(Inst->getOperand(0));
1030 printSimpleInstruction("mul");
1032 printSimpleInstruction("localloc");
1036 void MSILWriter::printInstruction(const Instruction* Inst) {
1037 const Value *Left = 0, *Right = 0;
1038 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1039 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1040 // Print instruction
1041 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1042 switch (Inst->getOpcode()) {
1044 case Instruction::Ret:
1045 if (Inst->getNumOperands()) {
1046 printValueLoad(Left);
1047 printSimpleInstruction("ret");
1049 printSimpleInstruction("ret");
1051 case Instruction::Br:
1052 printBranchInstruction(cast<BranchInst>(Inst));
1055 case Instruction::Add:
1056 printBinaryInstruction("add",Left,Right);
1058 case Instruction::Sub:
1059 printBinaryInstruction("sub",Left,Right);
1061 case Instruction::Mul:
1062 printBinaryInstruction("mul",Left,Right);
1064 case Instruction::UDiv:
1065 printBinaryInstruction("div.un",Left,Right);
1067 case Instruction::SDiv:
1068 case Instruction::FDiv:
1069 printBinaryInstruction("div",Left,Right);
1071 case Instruction::URem:
1072 printBinaryInstruction("rem.un",Left,Right);
1074 case Instruction::SRem:
1075 case Instruction::FRem:
1076 printBinaryInstruction("rem",Left,Right);
1079 case Instruction::ICmp:
1080 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1082 case Instruction::FCmp:
1083 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1086 case Instruction::And:
1087 printBinaryInstruction("and",Left,Right);
1089 case Instruction::Or:
1090 printBinaryInstruction("or",Left,Right);
1092 case Instruction::Xor:
1093 printBinaryInstruction("xor",Left,Right);
1095 case Instruction::Shl:
1096 printValueLoad(Left);
1097 printValueLoad(Right);
1098 printSimpleInstruction("conv.i4");
1099 printSimpleInstruction("shl");
1101 case Instruction::LShr:
1102 printValueLoad(Left);
1103 printValueLoad(Right);
1104 printSimpleInstruction("conv.i4");
1105 printSimpleInstruction("shr.un");
1107 case Instruction::AShr:
1108 printValueLoad(Left);
1109 printValueLoad(Right);
1110 printSimpleInstruction("conv.i4");
1111 printSimpleInstruction("shr");
1113 case Instruction::Select:
1114 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1116 case Instruction::Load:
1117 printIndirectLoad(Inst->getOperand(0));
1119 case Instruction::Store:
1120 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1122 case Instruction::Trunc:
1123 case Instruction::ZExt:
1124 case Instruction::SExt:
1125 case Instruction::FPTrunc:
1126 case Instruction::FPExt:
1127 case Instruction::UIToFP:
1128 case Instruction::SIToFP:
1129 case Instruction::FPToUI:
1130 case Instruction::FPToSI:
1131 case Instruction::PtrToInt:
1132 case Instruction::IntToPtr:
1133 case Instruction::BitCast:
1134 printCastInstruction(Inst->getOpcode(),Left,
1135 cast<CastInst>(Inst)->getDestTy());
1137 case Instruction::GetElementPtr:
1138 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1139 gep_type_end(Inst));
1141 case Instruction::Call:
1142 printCallInstruction(cast<CallInst>(Inst));
1144 case Instruction::Invoke:
1145 printInvokeInstruction(cast<InvokeInst>(Inst));
1147 case Instruction::Unwind:
1148 printSimpleInstruction("newobj",
1149 "instance void [mscorlib]System.Exception::.ctor()");
1150 printSimpleInstruction("throw");
1152 case Instruction::Switch:
1153 printSwitchInstruction(cast<SwitchInst>(Inst));
1155 case Instruction::Alloca:
1156 printAllocaInstruction(cast<AllocaInst>(Inst));
1158 case Instruction::Malloc:
1159 assert(0 && "LowerAllocationsPass used");
1161 case Instruction::Free:
1162 assert(0 && "LowerAllocationsPass used");
1164 case Instruction::Unreachable:
1165 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1166 printSimpleInstruction("newobj",
1167 "instance void [mscorlib]System.Exception::.ctor(string)");
1168 printSimpleInstruction("throw");
1170 case Instruction::VAArg:
1171 printVAArgInstruction(cast<VAArgInst>(Inst));
1174 cerr << "Instruction = " << Inst->getName() << '\n';
1175 assert(0 && "Unsupported instruction");
1180 void MSILWriter::printLoop(const Loop* L) {
1181 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1182 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1183 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1184 BasicBlock* BB = blocks[I];
1185 Loop* BBLoop = LInfo->getLoopFor(BB);
1187 printBasicBlock(BB);
1188 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1191 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1195 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1196 Out << getLabelName(BB) << ":\n";
1197 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1198 const Instruction* Inst = I;
1199 // Comment llvm original instruction
1200 // Out << "\n//" << *Inst << "\n";
1201 // Do not handle PHI instruction in current block
1202 if (Inst->getOpcode()==Instruction::PHI) continue;
1203 // Print instruction
1204 printInstruction(Inst);
1206 if (Inst->getType()!=Type::VoidTy) {
1207 // Do not save value after invoke, it done in "try" block
1208 if (Inst->getOpcode()==Instruction::Invoke) continue;
1209 printValueSave(Inst);
1215 void MSILWriter::printLocalVariables(const Function& F) {
1217 const Type* Ty = NULL;
1218 std::set<const Value*> Printed;
1219 const Value* VaList = NULL;
1220 unsigned StackDepth = 8;
1221 // Find local variables
1222 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1223 if (I->getOpcode()==Instruction::Call ||
1224 I->getOpcode()==Instruction::Invoke) {
1225 // Test stack depth.
1226 if (StackDepth<I->getNumOperands())
1227 StackDepth = I->getNumOperands();
1229 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1230 if (AI && !isa<GlobalVariable>(AI)) {
1231 // Local variable allocation.
1232 Ty = PointerType::getUnqual(AI->getAllocatedType());
1233 Name = getValueName(AI);
1234 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1235 } else if (I->getType()!=Type::VoidTy) {
1236 // Operation result.
1238 Name = getValueName(&*I);
1239 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1241 // Test on 'va_list' variable
1242 bool isVaList = false;
1243 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1244 // "va_list" as "va_arg" instruction operand.
1246 VaList = VaInst->getOperand(0);
1247 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1248 // "va_list" as intrinsic function operand.
1249 switch (Inst->getIntrinsicID()) {
1250 case Intrinsic::vastart:
1251 case Intrinsic::vaend:
1252 case Intrinsic::vacopy:
1254 VaList = Inst->getOperand(1);
1260 // Print "va_list" variable.
1261 if (isVaList && Printed.insert(VaList).second) {
1262 Name = getValueName(VaList);
1263 Name.insert(Name.length()-1,"$valist");
1264 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1268 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1272 void MSILWriter::printFunctionBody(const Function& F) {
1274 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1275 if (Loop *L = LInfo->getLoopFor(I)) {
1276 if (L->getHeader()==I && L->getParentLoop()==0)
1285 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1286 const Value *left = 0, *right = 0;
1287 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1288 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1289 // Print instruction
1290 switch (CE->getOpcode()) {
1291 case Instruction::Trunc:
1292 case Instruction::ZExt:
1293 case Instruction::SExt:
1294 case Instruction::FPTrunc:
1295 case Instruction::FPExt:
1296 case Instruction::UIToFP:
1297 case Instruction::SIToFP:
1298 case Instruction::FPToUI:
1299 case Instruction::FPToSI:
1300 case Instruction::PtrToInt:
1301 case Instruction::IntToPtr:
1302 case Instruction::BitCast:
1303 printCastInstruction(CE->getOpcode(),left,CE->getType());
1305 case Instruction::GetElementPtr:
1306 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1308 case Instruction::ICmp:
1309 printICmpInstruction(CE->getPredicate(),left,right);
1311 case Instruction::FCmp:
1312 printFCmpInstruction(CE->getPredicate(),left,right);
1314 case Instruction::Select:
1315 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1317 case Instruction::Add:
1318 printBinaryInstruction("add",left,right);
1320 case Instruction::Sub:
1321 printBinaryInstruction("sub",left,right);
1323 case Instruction::Mul:
1324 printBinaryInstruction("mul",left,right);
1326 case Instruction::UDiv:
1327 printBinaryInstruction("div.un",left,right);
1329 case Instruction::SDiv:
1330 case Instruction::FDiv:
1331 printBinaryInstruction("div",left,right);
1333 case Instruction::URem:
1334 printBinaryInstruction("rem.un",left,right);
1336 case Instruction::SRem:
1337 case Instruction::FRem:
1338 printBinaryInstruction("rem",left,right);
1340 case Instruction::And:
1341 printBinaryInstruction("and",left,right);
1343 case Instruction::Or:
1344 printBinaryInstruction("or",left,right);
1346 case Instruction::Xor:
1347 printBinaryInstruction("xor",left,right);
1349 case Instruction::Shl:
1350 printBinaryInstruction("shl",left,right);
1352 case Instruction::LShr:
1353 printBinaryInstruction("shr.un",left,right);
1355 case Instruction::AShr:
1356 printBinaryInstruction("shr",left,right);
1359 cerr << "Expression = " << *CE << "\n";
1360 assert(0 && "Invalid constant expression");
1365 void MSILWriter::printStaticInitializerList() {
1366 // List of global variables with uninitialized fields.
1367 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1368 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1370 const std::vector<StaticInitializer>& InitList = VarI->second;
1371 if (InitList.empty()) continue;
1372 // For each uninitialized field.
1373 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1374 E = InitList.end(); I!=E; ++I) {
1375 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1376 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1377 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1378 // Load variable address
1379 printValueLoad(VarI->first);
1382 printPtrLoad(I->offset);
1383 printSimpleInstruction("add");
1386 printConstantExpr(CE);
1387 // Save result at offset
1388 std::string postfix = getTypePostfix(CE->getType(),true);
1389 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1390 postfix = "stind."+postfix;
1391 printSimpleInstruction(postfix.c_str());
1393 cerr << "Constant = " << *I->constant << '\n';
1394 assert(0 && "Invalid static initializer");
1401 void MSILWriter::printFunction(const Function& F) {
1402 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1403 Out << "\n.method static ";
1404 Out << (F.hasLocalLinkage() ? "private " : "public ");
1405 if (F.isVarArg()) Out << "vararg ";
1406 Out << getTypeName(F.getReturnType(),isSigned) <<
1407 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1410 unsigned ArgIdx = 1;
1411 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1413 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1414 if (I!=F.arg_begin()) Out << ", ";
1415 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1417 Out << ") cil managed\n";
1420 printLocalVariables(F);
1421 printFunctionBody(F);
1426 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1428 std::set<const Type*> Printed;
1429 for (std::set<const Type*>::const_iterator
1430 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1431 const Type* Ty = *UI;
1432 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1433 Name = getTypeName(Ty, false, true);
1434 // Type with no need to declare.
1436 // Print not duplicated type
1437 if (Printed.insert(Ty).second) {
1438 Out << ".class value explicit ansi sealed '" << Name << "'";
1439 Out << " { .pack " << 1 << " .size " << TD->getTypePaddedSize(Ty);
1446 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1447 unsigned int N = Ty->getPrimitiveSizeInBits();
1448 assert(N!=0 && "Invalid type in getBitWidth()");
1457 cerr << "Bits = " << N << '\n';
1458 assert(0 && "Unsupported integer width");
1460 return 0; // Not reached
1464 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1465 uint64_t TySize = 0;
1466 const Type* Ty = C->getType();
1467 // Print zero initialized constant.
1468 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1469 TySize = TD->getTypePaddedSize(C->getType());
1471 Out << "int8 (0) [" << TySize << "]";
1474 // Print constant initializer
1475 switch (Ty->getTypeID()) {
1476 case Type::IntegerTyID: {
1477 TySize = TD->getTypePaddedSize(Ty);
1478 const ConstantInt* Int = cast<ConstantInt>(C);
1479 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1482 case Type::FloatTyID:
1483 case Type::DoubleTyID: {
1484 TySize = TD->getTypePaddedSize(Ty);
1485 const ConstantFP* FP = cast<ConstantFP>(C);
1486 if (Ty->getTypeID() == Type::FloatTyID)
1488 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1491 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1494 case Type::ArrayTyID:
1495 case Type::VectorTyID:
1496 case Type::StructTyID:
1497 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1498 if (I!=0) Out << ",\n";
1499 printStaticConstant(C->getOperand(I),Offset);
1502 case Type::PointerTyID:
1503 TySize = TD->getTypePaddedSize(C->getType());
1504 // Initialize with global variable address
1505 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1506 std::string name = getValueName(G);
1507 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1509 // Dynamic initialization
1510 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1511 InitListPtr->push_back(StaticInitializer(C,Offset));
1512 // Null pointer initialization
1513 if (TySize==4) Out << "int32 (0)";
1514 else if (TySize==8) Out << "int64 (0)";
1515 else assert(0 && "Invalid pointer size");
1519 cerr << "TypeID = " << Ty->getTypeID() << '\n';
1520 assert(0 && "Invalid type in printStaticConstant()");
1527 void MSILWriter::printStaticInitializer(const Constant* C,
1528 const std::string& Name) {
1529 switch (C->getType()->getTypeID()) {
1530 case Type::IntegerTyID:
1531 case Type::FloatTyID:
1532 case Type::DoubleTyID:
1533 Out << getPrimitiveTypeName(C->getType(), false);
1535 case Type::ArrayTyID:
1536 case Type::VectorTyID:
1537 case Type::StructTyID:
1538 case Type::PointerTyID:
1539 Out << getTypeName(C->getType());
1542 cerr << "Type = " << *C << "\n";
1543 assert(0 && "Invalid constant type");
1545 // Print initializer
1546 std::string label = Name;
1547 label.insert(label.length()-1,"$data");
1548 Out << Name << " at " << label << '\n';
1549 Out << ".data " << label << " = {\n";
1550 uint64_t offset = 0;
1551 printStaticConstant(C,offset);
1556 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1557 const Constant* C = G->getInitializer();
1558 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1561 InitListPtr = &StaticInitList[G];
1562 printStaticInitializer(C,getValueName(G));
1566 void MSILWriter::printGlobalVariables() {
1567 if (ModulePtr->global_empty()) return;
1568 Module::global_iterator I,E;
1569 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1570 // Variable definition
1571 Out << ".field static " << (I->isDeclaration() ? "public " :
1573 if (I->isDeclaration()) {
1574 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1576 printVariableDefinition(&*I);
1581 const char* MSILWriter::getLibraryName(const Function* F) {
1582 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1586 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1587 return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1591 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1592 unsigned CallingConv) {
1593 // TODO: Read *.def file with function and libraries definitions.
1594 return "MSVCRT.DLL";
1598 void MSILWriter::printExternals() {
1599 Module::const_iterator I,E;
1601 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1603 if (I->isIntrinsic()) continue;
1604 if (I->isDeclaration()) {
1605 const Function* F = I;
1606 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1608 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1609 Out << ".method static hidebysig pinvokeimpl(\""
1610 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1613 // External variables and static initialization.
1615 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1616 " native int LoadLibrary(string) preservesig {}\n"
1617 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1618 " native int GetProcAddress(native int, string) preservesig {}\n";
1620 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1623 "\tcall\tnative int LoadLibrary(string)\n"
1625 "\tcall\tnative int GetProcAddress(native int,string)\n"
1628 "\tldstr\t\"Can no import variable\"\n"
1629 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1634 ".method static private void $MSIL_Init() managed cil\n{\n";
1635 printStaticInitializerList();
1636 // Foreach global variable.
1637 for (Module::global_iterator I = ModulePtr->global_begin(),
1638 E = ModulePtr->global_end(); I!=E; ++I) {
1639 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1640 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1641 std::string Label = "not_null$_"+utostr(getUniqID());
1642 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1643 printSimpleInstruction("ldsflda",Tmp.c_str());
1644 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1645 Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1646 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1647 printIndirectSave(I->getType());
1649 printSimpleInstruction("ret");
1654 //===----------------------------------------------------------------------===//
1655 // External Interface declaration
1656 //===----------------------------------------------------------------------===//
1658 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
1659 CodeGenFileType FileType, bool Fast)
1661 if (FileType != TargetMachine::AssemblyFile) return true;
1662 MSILWriter* Writer = new MSILWriter(o);
1663 PM.add(createGCLoweringPass());
1664 PM.add(createLowerAllocationsPass(true));
1665 // FIXME: Handle switch trougth native IL instruction "switch"
1666 PM.add(createLowerSwitchPass());
1667 PM.add(createCFGSimplificationPass());
1668 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1670 PM.add(createGCInfoDeleter());