LLVM API Documentation

MSILWriter.cpp

Go to the documentation of this file.
00001 //===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library converts LLVM code to MSIL code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "MSILWriter.h"
00015 #include "llvm/CallingConv.h"
00016 #include "llvm/DerivedTypes.h"
00017 #include "llvm/Intrinsics.h"
00018 #include "llvm/IntrinsicInst.h"
00019 #include "llvm/TypeSymbolTable.h"
00020 #include "llvm/Analysis/ConstantsScanner.h"
00021 #include "llvm/Support/CallSite.h"
00022 #include "llvm/Support/ErrorHandling.h"
00023 #include "llvm/Support/InstVisitor.h"
00024 #include "llvm/Support/MathExtras.h"
00025 #include "llvm/Target/TargetRegistry.h"
00026 #include "llvm/Transforms/Scalar.h"
00027 #include "llvm/ADT/StringExtras.h"
00028 #include "llvm/CodeGen/Passes.h"
00029 using namespace llvm;
00030 
00031 namespace llvm {
00032   // TargetMachine for the MSIL 
00033   struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
00034     MSILTarget(const Target &T, const std::string &TT, const std::string &FS)
00035       : TargetMachine(T) {}
00036 
00037     virtual bool WantsWholeFile() const { return true; }
00038     virtual bool addPassesToEmitWholeFile(PassManager &PM,
00039                                           formatted_raw_ostream &Out,
00040                                           CodeGenFileType FileType,
00041                                           CodeGenOpt::Level OptLevel);
00042 
00043     virtual const TargetData *getTargetData() const { return 0; }
00044   };
00045 }
00046 
00047 extern "C" void LLVMInitializeMSILTarget() {
00048   // Register the target.
00049   RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
00050 }
00051 
00052 bool MSILModule::runOnModule(Module &M) {
00053   ModulePtr = &M;
00054   TD = &getAnalysis<TargetData>();
00055   bool Changed = false;
00056   // Find named types.  
00057   TypeSymbolTable& Table = M.getTypeSymbolTable();
00058   std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
00059   for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
00060     if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
00061       Table.remove(I++);
00062     else {
00063       std::set<const Type *>::iterator T = Types.find(I->second);
00064       if (T==Types.end())
00065         Table.remove(I++);
00066       else {
00067         Types.erase(T);
00068         ++I;
00069       }
00070     }
00071   }
00072   // Find unnamed types.
00073   unsigned RenameCounter = 0;
00074   for (std::set<const Type *>::const_iterator I = Types.begin(),
00075        E = Types.end(); I!=E; ++I)
00076     if (const StructType *STy = dyn_cast<StructType>(*I)) {
00077       while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
00078         ++RenameCounter;
00079       Changed = true;
00080     }
00081   // Pointer for FunctionPass.
00082   UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
00083   return Changed;
00084 }
00085 
00086 char MSILModule::ID = 0;
00087 char MSILWriter::ID = 0;
00088 
00089 bool MSILWriter::runOnFunction(Function &F) {
00090   if (F.isDeclaration()) return false;
00091 
00092   // Do not codegen any 'available_externally' functions at all, they have
00093   // definitions outside the translation unit.
00094   if (F.hasAvailableExternallyLinkage())
00095     return false;
00096 
00097   LInfo = &getAnalysis<LoopInfo>();
00098   printFunction(F);
00099   return false;
00100 }
00101 
00102 
00103 bool MSILWriter::doInitialization(Module &M) {
00104   ModulePtr = &M;
00105   Mang = new Mangler(M);
00106   Out << ".assembly extern mscorlib {}\n";
00107   Out << ".assembly MSIL {}\n\n";
00108   Out << "// External\n";
00109   printExternals();
00110   Out << "// Declarations\n";
00111   printDeclarations(M.getTypeSymbolTable());
00112   Out << "// Definitions\n";
00113   printGlobalVariables();
00114   Out << "// Startup code\n";
00115   printModuleStartup();
00116   return false;
00117 }
00118 
00119 
00120 bool MSILWriter::doFinalization(Module &M) {
00121   delete Mang;
00122   return false;
00123 }
00124 
00125 
00126 void MSILWriter::printModuleStartup() {
00127   Out <<
00128   ".method static public int32 $MSIL_Startup() {\n"
00129   "\t.entrypoint\n"
00130   "\t.locals (native int i)\n"
00131   "\t.locals (native int argc)\n"
00132   "\t.locals (native int ptr)\n"
00133   "\t.locals (void* argv)\n"
00134   "\t.locals (string[] args)\n"
00135   "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
00136   "\tdup\n"
00137   "\tstloc\targs\n"
00138   "\tldlen\n"
00139   "\tconv.i4\n"
00140   "\tdup\n"
00141   "\tstloc\targc\n";
00142   printPtrLoad(TD->getPointerSize());
00143   Out <<
00144   "\tmul\n"
00145   "\tlocalloc\n"
00146   "\tstloc\targv\n"
00147   "\tldc.i4.0\n"
00148   "\tstloc\ti\n"
00149   "L_01:\n"
00150   "\tldloc\ti\n"
00151   "\tldloc\targc\n"
00152   "\tceq\n"
00153   "\tbrtrue\tL_02\n"
00154   "\tldloc\targs\n"
00155   "\tldloc\ti\n"
00156   "\tldelem.ref\n"
00157   "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
00158            "StringToHGlobalAnsi(string)\n"
00159   "\tstloc\tptr\n"
00160   "\tldloc\targv\n"
00161   "\tldloc\ti\n";
00162   printPtrLoad(TD->getPointerSize());
00163   Out << 
00164   "\tmul\n"
00165   "\tadd\n"
00166   "\tldloc\tptr\n"
00167   "\tstind.i\n"
00168   "\tldloc\ti\n"
00169   "\tldc.i4.1\n"
00170   "\tadd\n"
00171   "\tstloc\ti\n"
00172   "\tbr\tL_01\n"
00173   "L_02:\n"
00174   "\tcall void $MSIL_Init()\n";
00175 
00176   // Call user 'main' function.
00177   const Function* F = ModulePtr->getFunction("main");
00178   if (!F || F->isDeclaration()) {
00179     Out << "\tldc.i4.0\n\tret\n}\n";
00180     return;
00181   }
00182   bool BadSig = true;
00183   std::string Args("");
00184   Function::const_arg_iterator Arg1,Arg2;
00185 
00186   switch (F->arg_size()) {
00187   case 0:
00188     BadSig = false;
00189     break;
00190   case 1:
00191     Arg1 = F->arg_begin();
00192     if (Arg1->getType()->isInteger()) {
00193       Out << "\tldloc\targc\n";
00194       Args = getTypeName(Arg1->getType());
00195       BadSig = false;
00196     }
00197     break;
00198   case 2:
00199     Arg1 = Arg2 = F->arg_begin(); ++Arg2;
00200     if (Arg1->getType()->isInteger() && 
00201         Arg2->getType()->getTypeID() == Type::PointerTyID) {
00202       Out << "\tldloc\targc\n\tldloc\targv\n";
00203       Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
00204       BadSig = false;
00205     }
00206     break;
00207   default:
00208     BadSig = true;
00209   }
00210 
00211   bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
00212   if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
00213     Out << "\tldc.i4.0\n";
00214   } else {
00215     Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
00216       getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
00217     if (RetVoid)
00218       Out << "\tldc.i4.0\n";
00219     else
00220       Out << "\tconv.i4\n";
00221   }
00222   Out << "\tret\n}\n";
00223 }
00224 
00225 bool MSILWriter::isZeroValue(const Value* V) {
00226   if (const Constant *C = dyn_cast<Constant>(V))
00227     return C->isNullValue();
00228   return false;
00229 }
00230 
00231 
00232 std::string MSILWriter::getValueName(const Value* V) {
00233   std::string Name;
00234   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
00235     Name = Mang->getMangledName(GV);
00236   else {
00237     unsigned &No = AnonValueNumbers[V];
00238     if (No == 0) No = ++NextAnonValueNumber;
00239     Name = "tmp" + utostr(No);
00240   }
00241   
00242   // Name into the quotes allow control and space characters.
00243   return "'"+Name+"'";
00244 }
00245 
00246 
00247 std::string MSILWriter::getLabelName(const std::string& Name) {
00248   if (Name.find('.')!=std::string::npos) {
00249     std::string Tmp(Name);
00250     // Replace unaccepable characters in the label name.
00251     for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
00252       if (*I=='.') *I = '@';
00253     return Tmp;
00254   }
00255   return Name;
00256 }
00257 
00258 
00259 std::string MSILWriter::getLabelName(const Value* V) {
00260   std::string Name;
00261   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
00262     Name = Mang->getMangledName(GV);
00263   else {
00264     unsigned &No = AnonValueNumbers[V];
00265     if (No == 0) No = ++NextAnonValueNumber;
00266     Name = "tmp" + utostr(No);
00267   }
00268   
00269   return getLabelName(Name);
00270 }
00271 
00272 
00273 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
00274   switch (CallingConvID) {
00275   case CallingConv::C:
00276   case CallingConv::Cold:
00277   case CallingConv::Fast:
00278     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
00279   case CallingConv::X86_FastCall:
00280     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
00281   case CallingConv::X86_StdCall:
00282     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
00283   default:
00284     cerr << "CallingConvID = " << CallingConvID << '\n';
00285     llvm_unreachable("Unsupported calling convention");
00286   }
00287   return ""; // Not reached
00288 }
00289 
00290 
00291 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
00292   std::string Tmp = "";
00293   const Type* ElemTy = Ty;
00294   assert(Ty->getTypeID()==TyID && "Invalid type passed");
00295   // Walk trought array element types.
00296   for (;;) {
00297     // Multidimensional array.
00298     if (ElemTy->getTypeID()==TyID) {
00299       if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
00300         Tmp += utostr(ATy->getNumElements());
00301       else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
00302         Tmp += utostr(VTy->getNumElements());
00303       ElemTy = cast<SequentialType>(ElemTy)->getElementType();
00304     }
00305     // Base element type found.
00306     if (ElemTy->getTypeID()!=TyID) break;
00307     Tmp += ",";
00308   }
00309   return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
00310 }
00311 
00312 
00313 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
00314   unsigned NumBits = 0;
00315   switch (Ty->getTypeID()) {
00316   case Type::VoidTyID:
00317     return "void ";
00318   case Type::IntegerTyID:
00319     NumBits = getBitWidth(Ty);
00320     if(NumBits==1)
00321       return "bool ";
00322     if (!isSigned)
00323       return "unsigned int"+utostr(NumBits)+" ";
00324     return "int"+utostr(NumBits)+" ";
00325   case Type::FloatTyID:
00326     return "float32 ";
00327   case Type::DoubleTyID:
00328     return "float64 "; 
00329   default:
00330     cerr << "Type = " << *Ty << '\n';
00331     llvm_unreachable("Invalid primitive type");
00332   }
00333   return ""; // Not reached
00334 }
00335 
00336 
00337 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
00338                                     bool isNested) {
00339   if (Ty->isPrimitiveType() || Ty->isInteger())
00340     return getPrimitiveTypeName(Ty,isSigned);
00341   // FIXME: "OpaqueType" support
00342   switch (Ty->getTypeID()) {
00343   case Type::PointerTyID:
00344     return "void* ";
00345   case Type::StructTyID:
00346     if (isNested)
00347       return ModulePtr->getTypeName(Ty);
00348     return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
00349   case Type::ArrayTyID:
00350     if (isNested)
00351       return getArrayTypeName(Ty->getTypeID(),Ty);
00352     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
00353   case Type::VectorTyID:
00354     if (isNested)
00355       return getArrayTypeName(Ty->getTypeID(),Ty);
00356     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
00357   default:
00358     cerr << "Type = " << *Ty << '\n';
00359     llvm_unreachable("Invalid type in getTypeName()");
00360   }
00361   return ""; // Not reached
00362 }
00363 
00364 
00365 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
00366   // Function argument
00367   if (isa<Argument>(V))
00368     return ArgumentVT;
00369   // Function
00370   else if (const Function* F = dyn_cast<Function>(V))
00371     return F->hasLocalLinkage() ? InternalVT : GlobalVT;
00372   // Variable
00373   else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
00374     return G->hasLocalLinkage() ? InternalVT : GlobalVT;
00375   // Constant
00376   else if (isa<Constant>(V))
00377     return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
00378   // Local variable
00379   return LocalVT;
00380 }
00381 
00382 
00383 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
00384                                        bool isSigned) {
00385   unsigned NumBits = 0;
00386   switch (Ty->getTypeID()) {
00387   // Integer constant, expanding for stack operations.
00388   case Type::IntegerTyID:
00389     NumBits = getBitWidth(Ty);
00390     // Expand integer value to "int32" or "int64".
00391     if (Expand) return (NumBits<=32 ? "i4" : "i8");
00392     if (NumBits==1) return "i1";
00393     return (isSigned ? "i" : "u")+utostr(NumBits/8);
00394   // Float constant.
00395   case Type::FloatTyID:
00396     return "r4";
00397   case Type::DoubleTyID:
00398     return "r8";
00399   case Type::PointerTyID:
00400     return "i"+utostr(TD->getTypeAllocSize(Ty));
00401   default:
00402     cerr << "TypeID = " << Ty->getTypeID() << '\n';
00403     llvm_unreachable("Invalid type in TypeToPostfix()");
00404   }
00405   return ""; // Not reached
00406 }
00407 
00408 
00409 void MSILWriter::printConvToPtr() {
00410   switch (ModulePtr->getPointerSize()) {
00411   case Module::Pointer32:
00412     printSimpleInstruction("conv.u4");
00413     break;
00414   case Module::Pointer64:
00415     printSimpleInstruction("conv.u8");
00416     break;
00417   default:
00418     llvm_unreachable("Module use not supporting pointer size");
00419   }
00420 }
00421 
00422 
00423 void MSILWriter::printPtrLoad(uint64_t N) {
00424   switch (ModulePtr->getPointerSize()) {
00425   case Module::Pointer32:
00426     printSimpleInstruction("ldc.i4",utostr(N).c_str());
00427     // FIXME: Need overflow test?
00428     if (!isUInt32(N)) {
00429       cerr << "Value = " << utostr(N) << '\n';
00430       llvm_unreachable("32-bit pointer overflowed");
00431     }
00432     break;
00433   case Module::Pointer64:
00434     printSimpleInstruction("ldc.i8",utostr(N).c_str());
00435     break;
00436   default:
00437     llvm_unreachable("Module use not supporting pointer size");
00438   }
00439 }
00440 
00441 
00442 void MSILWriter::printValuePtrLoad(const Value* V) {
00443   printValueLoad(V);
00444   printConvToPtr();
00445 }
00446 
00447 
00448 void MSILWriter::printConstLoad(const Constant* C) {
00449   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
00450     // Integer constant
00451     Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
00452     if (CInt->isMinValue(true))
00453       Out << CInt->getSExtValue();
00454     else
00455       Out << CInt->getZExtValue();
00456   } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
00457     // Float constant
00458     uint64_t X;
00459     unsigned Size;
00460     if (FP->getType()->getTypeID()==Type::FloatTyID) {
00461       X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
00462       Size = 4;  
00463     } else {
00464       X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
00465       Size = 8;  
00466     }
00467     Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
00468   } else if (isa<UndefValue>(C)) {
00469     // Undefined constant value = NULL.
00470     printPtrLoad(0);
00471   } else {
00472     cerr << "Constant = " << *C << '\n';
00473     llvm_unreachable("Invalid constant value");
00474   }
00475   Out << '\n';
00476 }
00477 
00478 
00479 void MSILWriter::printValueLoad(const Value* V) {
00480   MSILWriter::ValueType Location = getValueLocation(V);
00481   switch (Location) {
00482   // Global variable or function address.
00483   case GlobalVT:
00484   case InternalVT:
00485     if (const Function* F = dyn_cast<Function>(V)) {
00486       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
00487       printSimpleInstruction("ldftn",
00488         getCallSignature(F->getFunctionType(),NULL,Name).c_str());
00489     } else {
00490       std::string Tmp;
00491       const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
00492       if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
00493         Tmp = "void* "+getValueName(V);
00494         printSimpleInstruction("ldsfld",Tmp.c_str());
00495       } else {
00496         Tmp = getTypeName(ElemTy)+getValueName(V);
00497         printSimpleInstruction("ldsflda",Tmp.c_str());
00498       }
00499     }
00500     break;
00501   // Function argument.
00502   case ArgumentVT:
00503     printSimpleInstruction("ldarg",getValueName(V).c_str());
00504     break;
00505   // Local function variable.
00506   case LocalVT:
00507     printSimpleInstruction("ldloc",getValueName(V).c_str());
00508     break;
00509   // Constant value.
00510   case ConstVT:
00511     if (isa<ConstantPointerNull>(V))
00512       printPtrLoad(0);
00513     else
00514       printConstLoad(cast<Constant>(V));
00515     break;
00516   // Constant expression.
00517   case ConstExprVT:
00518     printConstantExpr(cast<ConstantExpr>(V));
00519     break;
00520   default:
00521     cerr << "Value = " << *V << '\n';
00522     llvm_unreachable("Invalid value location");
00523   }
00524 }
00525 
00526 
00527 void MSILWriter::printValueSave(const Value* V) {
00528   switch (getValueLocation(V)) {
00529   case ArgumentVT:
00530     printSimpleInstruction("starg",getValueName(V).c_str());
00531     break;
00532   case LocalVT:
00533     printSimpleInstruction("stloc",getValueName(V).c_str());
00534     break;
00535   default:
00536     cerr << "Value  = " << *V << '\n';
00537     llvm_unreachable("Invalid value location");
00538   }
00539 }
00540 
00541 
00542 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
00543                                         const Value* Right) {
00544   printValueLoad(Left);
00545   printValueLoad(Right);
00546   Out << '\t' << Name << '\n';
00547 }
00548 
00549 
00550 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
00551   if(Operand) 
00552     Out << '\t' << Inst << '\t' << Operand << '\n';
00553   else
00554     Out << '\t' << Inst << '\n';
00555 }
00556 
00557 
00558 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
00559   for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
00560        isa<PHINode>(I); ++I) {
00561     const PHINode* Phi = cast<PHINode>(I);
00562     const Value* Val = Phi->getIncomingValueForBlock(Src);
00563     if (isa<UndefValue>(Val)) continue;
00564     printValueLoad(Val);
00565     printValueSave(Phi);
00566   }
00567 }
00568 
00569 
00570 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
00571                                     const BasicBlock* TrueBB,
00572                                     const BasicBlock* FalseBB) {
00573   if (TrueBB==FalseBB) {
00574     // "TrueBB" and "FalseBB" destination equals
00575     printPHICopy(CurrBB,TrueBB);
00576     printSimpleInstruction("pop");
00577     printSimpleInstruction("br",getLabelName(TrueBB).c_str());
00578   } else if (FalseBB==NULL) {
00579     // If "FalseBB" not used the jump have condition
00580     printPHICopy(CurrBB,TrueBB);
00581     printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
00582   } else if (TrueBB==NULL) {
00583     // If "TrueBB" not used the jump is unconditional
00584     printPHICopy(CurrBB,FalseBB);
00585     printSimpleInstruction("br",getLabelName(FalseBB).c_str());
00586   } else {
00587     // Copy PHI instructions for each block
00588     std::string TmpLabel;
00589     // Print PHI instructions for "TrueBB"
00590     if (isa<PHINode>(TrueBB->begin())) {
00591       TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
00592       printSimpleInstruction("brtrue",TmpLabel.c_str());
00593     } else {
00594       printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
00595     }
00596     // Print PHI instructions for "FalseBB"
00597     if (isa<PHINode>(FalseBB->begin())) {
00598       printPHICopy(CurrBB,FalseBB);
00599       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
00600     } else {
00601       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
00602     }
00603     if (isa<PHINode>(TrueBB->begin())) {
00604       // Handle "TrueBB" PHI Copy
00605       Out << TmpLabel << ":\n";
00606       printPHICopy(CurrBB,TrueBB);
00607       printSimpleInstruction("br",getLabelName(TrueBB).c_str());
00608     }
00609   }
00610 }
00611 
00612 
00613 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
00614   if (Inst->isUnconditional()) {
00615     printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
00616   } else {
00617     printValueLoad(Inst->getCondition());
00618     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
00619                        Inst->getSuccessor(1));
00620   }
00621 }
00622 
00623 
00624 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
00625                                         const Value* VFalse) {
00626   std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
00627   printValueLoad(VTrue);
00628   printValueLoad(Cond);
00629   printSimpleInstruction("brtrue",TmpLabel.c_str());
00630   printSimpleInstruction("pop");
00631   printValueLoad(VFalse);
00632   Out << TmpLabel << ":\n";
00633 }
00634 
00635 
00636 void MSILWriter::printIndirectLoad(const Value* V) {
00637   const Type* Ty = V->getType();
00638   printValueLoad(V);
00639   if (const PointerType* P = dyn_cast<PointerType>(Ty))
00640     Ty = P->getElementType();
00641   std::string Tmp = "ldind."+getTypePostfix(Ty, false);
00642   printSimpleInstruction(Tmp.c_str());
00643 }
00644 
00645 
00646 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
00647   printValueLoad(Ptr);
00648   printValueLoad(Val);
00649   printIndirectSave(Val->getType());
00650 }
00651 
00652 
00653 void MSILWriter::printIndirectSave(const Type* Ty) {
00654   // Instruction need signed postfix for any type.
00655   std::string postfix = getTypePostfix(Ty, false);
00656   if (*postfix.begin()=='u') *postfix.begin() = 'i';
00657   postfix = "stind."+postfix;
00658   printSimpleInstruction(postfix.c_str());
00659 }
00660 
00661 
00662 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
00663                                       const Type* Ty, const Type* SrcTy) {
00664   std::string Tmp("");
00665   printValueLoad(V);
00666   switch (Op) {
00667   // Signed
00668   case Instruction::SExt:
00669     // If sign extending int, convert first from unsigned to signed
00670     // with the same bit size - because otherwise we will loose the sign.
00671     if (SrcTy) {
00672       Tmp = "conv."+getTypePostfix(SrcTy,false,true);
00673       printSimpleInstruction(Tmp.c_str());
00674     }
00675     // FALLTHROUGH
00676   case Instruction::SIToFP:
00677   case Instruction::FPToSI:
00678     Tmp = "conv."+getTypePostfix(Ty,false,true);
00679     printSimpleInstruction(Tmp.c_str());
00680     break;
00681   // Unsigned
00682   case Instruction::FPTrunc:
00683   case Instruction::FPExt:
00684   case Instruction::UIToFP:
00685   case Instruction::Trunc:
00686   case Instruction::ZExt:
00687   case Instruction::FPToUI:
00688   case Instruction::PtrToInt:
00689   case Instruction::IntToPtr:
00690     Tmp = "conv."+getTypePostfix(Ty,false);
00691     printSimpleInstruction(Tmp.c_str());
00692     break;
00693   // Do nothing
00694   case Instruction::BitCast:
00695     // FIXME: meaning that ld*/st* instruction do not change data format.
00696     break;
00697   default:
00698     cerr << "Opcode = " << Op << '\n';
00699     llvm_unreachable("Invalid conversion instruction");
00700   }
00701 }
00702 
00703 
00704 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
00705                                      gep_type_iterator E) {
00706   unsigned Size;
00707   // Load address
00708   printValuePtrLoad(V);
00709   // Calculate element offset.
00710   for (; I!=E; ++I){
00711     Size = 0;
00712     const Value* IndexValue = I.getOperand();
00713     if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
00714       uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
00715       // Offset is the sum of all previous structure fields.
00716       for (uint64_t F = 0; F<FieldIndex; ++F)
00717         Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
00718       printPtrLoad(Size);
00719       printSimpleInstruction("add");
00720       continue;
00721     } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
00722       Size = TD->getTypeAllocSize(SeqTy->getElementType());
00723     } else {
00724       Size = TD->getTypeAllocSize(*I);
00725     }
00726     // Add offset of current element to stack top.
00727     if (!isZeroValue(IndexValue)) {
00728       // Constant optimization.
00729       if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
00730         if (C->getValue().isNegative()) {
00731           printPtrLoad(C->getValue().abs().getZExtValue()*Size);
00732           printSimpleInstruction("sub");
00733           continue;
00734         } else
00735           printPtrLoad(C->getZExtValue()*Size);
00736       } else {
00737         printPtrLoad(Size);
00738         printValuePtrLoad(IndexValue);
00739         printSimpleInstruction("mul");
00740       }
00741       printSimpleInstruction("add");
00742     }
00743   }
00744 }
00745 
00746 
00747 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
00748                                          const Instruction* Inst,
00749                                          std::string Name) {
00750   std::string Tmp("");
00751   if (Ty->isVarArg()) Tmp += "vararg ";
00752   // Name and return type.
00753   Tmp += getTypeName(Ty->getReturnType())+Name+"(";
00754   // Function argument type list.
00755   unsigned NumParams = Ty->getNumParams();
00756   for (unsigned I = 0; I!=NumParams; ++I) {
00757     if (I!=0) Tmp += ",";
00758     Tmp += getTypeName(Ty->getParamType(I));
00759   }
00760   // CLR needs to know the exact amount of parameters received by vararg
00761   // function, because caller cleans the stack.
00762   if (Ty->isVarArg() && Inst) {
00763     // Origin to function arguments in "CallInst" or "InvokeInst".
00764     unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
00765     // Print variable argument types.
00766     unsigned NumOperands = Inst->getNumOperands()-Org;
00767     if (NumParams<NumOperands) {
00768       if (NumParams!=0) Tmp += ", ";
00769       Tmp += "... , ";
00770       for (unsigned J = NumParams; J!=NumOperands; ++J) {
00771         if (J!=NumParams) Tmp += ", ";
00772         Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
00773       }
00774     }
00775   }
00776   return Tmp+")";
00777 }
00778 
00779 
00780 void MSILWriter::printFunctionCall(const Value* FnVal,
00781                                    const Instruction* Inst) {
00782   // Get function calling convention.
00783   std::string Name = "";
00784   if (const CallInst* Call = dyn_cast<CallInst>(Inst))
00785     Name = getConvModopt(Call->getCallingConv());
00786   else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
00787     Name = getConvModopt(Invoke->getCallingConv());
00788   else {
00789     errs() << "Instruction = " << Inst->getName() << '\n';
00790     llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
00791   }
00792   if (const Function* F = dyn_cast<Function>(FnVal)) {
00793     // Direct call.
00794     Name += getValueName(F);
00795     printSimpleInstruction("call",
00796       getCallSignature(F->getFunctionType(),Inst,Name).c_str());
00797   } else {
00798     // Indirect function call.
00799     const PointerType* PTy = cast<PointerType>(FnVal->getType());
00800     const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
00801     // Load function address.
00802     printValueLoad(FnVal);
00803     printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
00804   }
00805 }
00806 
00807 
00808 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
00809   std::string Name;
00810   switch (Inst->getIntrinsicID()) {
00811   case Intrinsic::vastart:
00812     Name = getValueName(Inst->getOperand(1));
00813     Name.insert(Name.length()-1,"$valist");
00814     // Obtain the argument handle.
00815     printSimpleInstruction("ldloca",Name.c_str());
00816     printSimpleInstruction("arglist");
00817     printSimpleInstruction("call",
00818       "instance void [mscorlib]System.ArgIterator::.ctor"
00819       "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
00820     // Save as pointer type "void*"
00821     printValueLoad(Inst->getOperand(1));
00822     printSimpleInstruction("ldloca",Name.c_str());
00823     printIndirectSave(PointerType::getUnqual(
00824           IntegerType::get(Inst->getContext(), 8)));
00825     break;
00826   case Intrinsic::vaend:
00827     // Close argument list handle.
00828     printIndirectLoad(Inst->getOperand(1));
00829     printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
00830     break;
00831   case Intrinsic::vacopy:
00832     // Copy "ArgIterator" valuetype.
00833     printIndirectLoad(Inst->getOperand(1));
00834     printIndirectLoad(Inst->getOperand(2));
00835     printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
00836     break;        
00837   default:
00838     errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
00839     llvm_unreachable("Invalid intrinsic function");
00840   }
00841 }
00842 
00843 
00844 void MSILWriter::printCallInstruction(const Instruction* Inst) {
00845   if (isa<IntrinsicInst>(Inst)) {
00846     // Handle intrinsic function.
00847     printIntrinsicCall(cast<IntrinsicInst>(Inst));
00848   } else {
00849     // Load arguments to stack and call function.
00850     for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
00851       printValueLoad(Inst->getOperand(I));
00852     printFunctionCall(Inst->getOperand(0),Inst);
00853   }
00854 }
00855 
00856 
00857 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
00858                                       const Value* Right) {
00859   switch (Predicate) {
00860   case ICmpInst::ICMP_EQ:
00861     printBinaryInstruction("ceq",Left,Right);
00862     break;
00863   case ICmpInst::ICMP_NE:
00864     // Emulate = not neg (Op1 eq Op2)
00865     printBinaryInstruction("ceq",Left,Right);
00866     printSimpleInstruction("neg");
00867     printSimpleInstruction("not");
00868     break;
00869   case ICmpInst::ICMP_ULE:
00870   case ICmpInst::ICMP_SLE:
00871     // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
00872     printBinaryInstruction("ceq",Left,Right);
00873     if (Predicate==ICmpInst::ICMP_ULE)
00874       printBinaryInstruction("clt.un",Left,Right);
00875     else
00876       printBinaryInstruction("clt",Left,Right);
00877     printSimpleInstruction("or");
00878     break;
00879   case ICmpInst::ICMP_UGE:
00880   case ICmpInst::ICMP_SGE:
00881     // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
00882     printBinaryInstruction("ceq",Left,Right);
00883     if (Predicate==ICmpInst::ICMP_UGE)
00884       printBinaryInstruction("cgt.un",Left,Right);
00885     else
00886       printBinaryInstruction("cgt",Left,Right);
00887     printSimpleInstruction("or");
00888     break;
00889   case ICmpInst::ICMP_ULT:
00890     printBinaryInstruction("clt.un",Left,Right);
00891     break;
00892   case ICmpInst::ICMP_SLT:
00893     printBinaryInstruction("clt",Left,Right);
00894     break;
00895   case ICmpInst::ICMP_UGT:
00896     printBinaryInstruction("cgt.un",Left,Right);
00897     break;
00898   case ICmpInst::ICMP_SGT:
00899     printBinaryInstruction("cgt",Left,Right);
00900     break;
00901   default:
00902     errs() << "Predicate = " << Predicate << '\n';
00903     llvm_unreachable("Invalid icmp predicate");
00904   }
00905 }
00906 
00907 
00908 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
00909                                       const Value* Right) {
00910   // FIXME: Correct comparison
00911   std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
00912   switch (Predicate) {
00913   case FCmpInst::FCMP_UGT:
00914     // X >  Y || llvm_fcmp_uno(X, Y)
00915     printBinaryInstruction("cgt",Left,Right);
00916     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
00917     printSimpleInstruction("or");
00918     break;
00919   case FCmpInst::FCMP_OGT:
00920     // X >  Y
00921     printBinaryInstruction("cgt",Left,Right);
00922     break;
00923   case FCmpInst::FCMP_UGE:
00924     // X >= Y || llvm_fcmp_uno(X, Y)
00925     printBinaryInstruction("ceq",Left,Right);
00926     printBinaryInstruction("cgt",Left,Right);
00927     printSimpleInstruction("or");
00928     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
00929     printSimpleInstruction("or");
00930     break;
00931   case FCmpInst::FCMP_OGE:
00932     // X >= Y
00933     printBinaryInstruction("ceq",Left,Right);
00934     printBinaryInstruction("cgt",Left,Right);
00935     printSimpleInstruction("or");
00936     break;
00937   case FCmpInst::FCMP_ULT:
00938     // X <  Y || llvm_fcmp_uno(X, Y)
00939     printBinaryInstruction("clt",Left,Right);
00940     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
00941     printSimpleInstruction("or");
00942     break;
00943   case FCmpInst::FCMP_OLT:
00944     // X <  Y
00945     printBinaryInstruction("clt",Left,Right);
00946     break;
00947   case FCmpInst::FCMP_ULE:
00948     // X <= Y || llvm_fcmp_uno(X, Y)
00949     printBinaryInstruction("ceq",Left,Right);
00950     printBinaryInstruction("clt",Left,Right);
00951     printSimpleInstruction("or");
00952     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
00953     printSimpleInstruction("or");
00954     break;
00955   case FCmpInst::FCMP_OLE:
00956     // X <= Y
00957     printBinaryInstruction("ceq",Left,Right);
00958     printBinaryInstruction("clt",Left,Right);
00959     printSimpleInstruction("or");
00960     break;
00961   case FCmpInst::FCMP_UEQ:
00962     // X == Y || llvm_fcmp_uno(X, Y)
00963     printBinaryInstruction("ceq",Left,Right);
00964     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
00965     printSimpleInstruction("or");
00966     break;
00967   case FCmpInst::FCMP_OEQ:
00968     // X == Y
00969     printBinaryInstruction("ceq",Left,Right);
00970     break;
00971   case FCmpInst::FCMP_UNE:
00972     // X != Y
00973     printBinaryInstruction("ceq",Left,Right);
00974     printSimpleInstruction("neg");
00975     printSimpleInstruction("not");
00976     break;
00977   case FCmpInst::FCMP_ONE:
00978     // X != Y && llvm_fcmp_ord(X, Y)
00979     printBinaryInstruction("ceq",Left,Right);
00980     printSimpleInstruction("not");
00981     break;
00982   case FCmpInst::FCMP_ORD:
00983     // return X == X && Y == Y
00984     printBinaryInstruction("ceq",Left,Left);
00985     printBinaryInstruction("ceq",Right,Right);
00986     printSimpleInstruction("or");
00987     break;
00988   case FCmpInst::FCMP_UNO:
00989     // X != X || Y != Y
00990     printBinaryInstruction("ceq",Left,Left);
00991     printSimpleInstruction("not");
00992     printBinaryInstruction("ceq",Right,Right);
00993     printSimpleInstruction("not");
00994     printSimpleInstruction("or");
00995     break;
00996   default:
00997     llvm_unreachable("Illegal FCmp predicate");
00998   }
00999 }
01000 
01001 
01002 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
01003   std::string Label = "leave$normal_"+utostr(getUniqID());
01004   Out << ".try {\n";
01005   // Load arguments
01006   for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
01007     printValueLoad(Inst->getOperand(I));
01008   // Print call instruction
01009   printFunctionCall(Inst->getOperand(0),Inst);
01010   // Save function result and leave "try" block
01011   printValueSave(Inst);
01012   printSimpleInstruction("leave",Label.c_str());
01013   Out << "}\n";
01014   Out << "catch [mscorlib]System.Exception {\n";
01015   // Redirect to unwind block
01016   printSimpleInstruction("pop");
01017   printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
01018   Out << "}\n" << Label << ":\n";
01019   // Redirect to continue block
01020   printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
01021 }
01022 
01023 
01024 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
01025   // FIXME: Emulate with IL "switch" instruction
01026   // Emulate = if () else if () else if () else ...
01027   for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
01028     printValueLoad(Inst->getCondition());
01029     printValueLoad(Inst->getCaseValue(I));
01030     printSimpleInstruction("ceq");
01031     // Condition jump to successor block
01032     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
01033   }
01034   // Jump to default block
01035   printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
01036 }
01037 
01038 
01039 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
01040   printIndirectLoad(Inst->getOperand(0));
01041   printSimpleInstruction("call",
01042     "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
01043   printSimpleInstruction("refanyval","void*");
01044   std::string Name = 
01045     "ldind."+getTypePostfix(PointerType::getUnqual(
01046             IntegerType::get(Inst->getContext(), 8)),false);
01047   printSimpleInstruction(Name.c_str());
01048 }
01049 
01050 
01051 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
01052   uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
01053   // Constant optimization.
01054   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
01055     printPtrLoad(CInt->getZExtValue()*Size);
01056   } else {
01057     printPtrLoad(Size);
01058     printValueLoad(Inst->getOperand(0));
01059     printSimpleInstruction("mul");
01060   }
01061   printSimpleInstruction("localloc");
01062 }
01063 
01064 
01065 void MSILWriter::printInstruction(const Instruction* Inst) {
01066   const Value *Left = 0, *Right = 0;
01067   if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
01068   if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
01069   // Print instruction
01070   // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
01071   switch (Inst->getOpcode()) {
01072   // Terminator
01073   case Instruction::Ret:
01074     if (Inst->getNumOperands()) {
01075       printValueLoad(Left);
01076       printSimpleInstruction("ret");
01077     } else
01078       printSimpleInstruction("ret");
01079     break;
01080   case Instruction::Br:
01081     printBranchInstruction(cast<BranchInst>(Inst));
01082     break;
01083   // Binary
01084   case Instruction::Add:
01085   case Instruction::FAdd:
01086     printBinaryInstruction("add",Left,Right);
01087     break;
01088   case Instruction::Sub:
01089   case Instruction::FSub:
01090     printBinaryInstruction("sub",Left,Right);
01091     break;
01092   case Instruction::Mul:
01093   case Instruction::FMul:
01094     printBinaryInstruction("mul",Left,Right);
01095     break;
01096   case Instruction::UDiv:
01097     printBinaryInstruction("div.un",Left,Right);
01098     break;
01099   case Instruction::SDiv:
01100   case Instruction::FDiv:
01101     printBinaryInstruction("div",Left,Right);
01102     break;
01103   case Instruction::URem:
01104     printBinaryInstruction("rem.un",Left,Right);
01105     break;
01106   case Instruction::SRem:
01107   case Instruction::FRem:
01108     printBinaryInstruction("rem",Left,Right);
01109     break;
01110   // Binary Condition
01111   case Instruction::ICmp:
01112     printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
01113     break;
01114   case Instruction::FCmp:
01115     printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
01116     break;
01117   // Bitwise Binary
01118   case Instruction::And:
01119     printBinaryInstruction("and",Left,Right);
01120     break;
01121   case Instruction::Or:
01122     printBinaryInstruction("or",Left,Right);
01123     break;
01124   case Instruction::Xor:
01125     printBinaryInstruction("xor",Left,Right);
01126     break;
01127   case Instruction::Shl:
01128     printValueLoad(Left);
01129     printValueLoad(Right);
01130     printSimpleInstruction("conv.i4");
01131     printSimpleInstruction("shl");
01132     break;
01133   case Instruction::LShr:
01134     printValueLoad(Left);
01135     printValueLoad(Right);
01136     printSimpleInstruction("conv.i4");
01137     printSimpleInstruction("shr.un");
01138     break;
01139   case Instruction::AShr:
01140     printValueLoad(Left);
01141     printValueLoad(Right);
01142     printSimpleInstruction("conv.i4");
01143     printSimpleInstruction("shr");
01144     break;
01145   case Instruction::Select:
01146     printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
01147     break;
01148   case Instruction::Load:
01149     printIndirectLoad(Inst->getOperand(0));
01150     break;
01151   case Instruction::Store:
01152     printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
01153     break;
01154   case Instruction::SExt:
01155     printCastInstruction(Inst->getOpcode(),Left,
01156                          cast<CastInst>(Inst)->getDestTy(),
01157                          cast<CastInst>(Inst)->getSrcTy());
01158     break;
01159   case Instruction::Trunc:
01160   case Instruction::ZExt:
01161   case Instruction::FPTrunc:
01162   case Instruction::FPExt:
01163   case Instruction::UIToFP:
01164   case Instruction::SIToFP:
01165   case Instruction::FPToUI:
01166   case Instruction::FPToSI:
01167   case Instruction::PtrToInt:
01168   case Instruction::IntToPtr:
01169   case Instruction::BitCast:
01170     printCastInstruction(Inst->getOpcode(),Left,
01171                          cast<CastInst>(Inst)->getDestTy());
01172     break;
01173   case Instruction::GetElementPtr:
01174     printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
01175                         gep_type_end(Inst));
01176     break;
01177   case Instruction::Call:
01178     printCallInstruction(cast<CallInst>(Inst));
01179     break;
01180   case Instruction::Invoke:
01181     printInvokeInstruction(cast<InvokeInst>(Inst));
01182     break;
01183   case Instruction::Unwind:
01184     printSimpleInstruction("newobj",
01185       "instance void [mscorlib]System.Exception::.ctor()");
01186     printSimpleInstruction("throw");
01187     break;
01188   case Instruction::Switch:
01189     printSwitchInstruction(cast<SwitchInst>(Inst));
01190     break;
01191   case Instruction::Alloca:
01192     printAllocaInstruction(cast<AllocaInst>(Inst));
01193     break;
01194   case Instruction::Malloc:
01195     llvm_unreachable("LowerAllocationsPass used");
01196     break;
01197   case Instruction::Free:
01198     llvm_unreachable("LowerAllocationsPass used");
01199     break;
01200   case Instruction::Unreachable:
01201     printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
01202     printSimpleInstruction("newobj",
01203       "instance void [mscorlib]System.Exception::.ctor(string)");
01204     printSimpleInstruction("throw");
01205     break;
01206   case Instruction::VAArg:
01207     printVAArgInstruction(cast<VAArgInst>(Inst));
01208     break;
01209   default:
01210     errs() << "Instruction = " << Inst->getName() << '\n';
01211     llvm_unreachable("Unsupported instruction");
01212   }
01213 }
01214 
01215 
01216 void MSILWriter::printLoop(const Loop* L) {
01217   Out << getLabelName(L->getHeader()->getName()) << ":\n";
01218   const std::vector<BasicBlock*>& blocks = L->getBlocks();
01219   for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
01220     BasicBlock* BB = blocks[I];
01221     Loop* BBLoop = LInfo->getLoopFor(BB);
01222     if (BBLoop == L)
01223       printBasicBlock(BB);
01224     else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
01225       printLoop(BBLoop);
01226   }
01227   printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
01228 }
01229 
01230 
01231 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
01232   Out << getLabelName(BB) << ":\n";
01233   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
01234     const Instruction* Inst = I;
01235     // Comment llvm original instruction
01236     // Out << "\n//" << *Inst << "\n";
01237     // Do not handle PHI instruction in current block
01238     if (Inst->getOpcode()==Instruction::PHI) continue;
01239     // Print instruction
01240     printInstruction(Inst);
01241     // Save result
01242     if (Inst->getType()!=Type::getVoidTy(BB->getContext())) {
01243       // Do not save value after invoke, it done in "try" block
01244       if (Inst->getOpcode()==Instruction::Invoke) continue;
01245       printValueSave(Inst);
01246     }
01247   }
01248 }
01249 
01250 
01251 void MSILWriter::printLocalVariables(const Function& F) {
01252   std::string Name;
01253   const Type* Ty = NULL;
01254   std::set<const Value*> Printed;
01255   const Value* VaList = NULL;
01256   unsigned StackDepth = 8;
01257   // Find local variables
01258   for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
01259     if (I->getOpcode()==Instruction::Call ||
01260         I->getOpcode()==Instruction::Invoke) {
01261       // Test stack depth.
01262       if (StackDepth<I->getNumOperands())
01263         StackDepth = I->getNumOperands();
01264     }
01265     const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
01266     if (AI && !isa<GlobalVariable>(AI)) {
01267       // Local variable allocation.
01268       Ty = PointerType::getUnqual(AI->getAllocatedType());
01269       Name = getValueName(AI);
01270       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
01271     } else if (I->getType()!=Type::getVoidTy(F.getContext())) {
01272       // Operation result.
01273       Ty = I->getType();
01274       Name = getValueName(&*I);
01275       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
01276     }
01277     // Test on 'va_list' variable    
01278     bool isVaList = false;     
01279     if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
01280       // "va_list" as "va_arg" instruction operand.
01281       isVaList = true;
01282       VaList = VaInst->getOperand(0);
01283     } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
01284       // "va_list" as intrinsic function operand. 
01285       switch (Inst->getIntrinsicID()) {
01286       case Intrinsic::vastart:
01287       case Intrinsic::vaend:
01288       case Intrinsic::vacopy:
01289         isVaList = true;
01290         VaList = Inst->getOperand(1);
01291         break;
01292       default:
01293         isVaList = false;
01294       }
01295     }
01296     // Print "va_list" variable.
01297     if (isVaList && Printed.insert(VaList).second) {
01298       Name = getValueName(VaList);
01299       Name.insert(Name.length()-1,"$valist");
01300       Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
01301           << Name << ")\n";
01302     }
01303   }
01304   printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
01305 }
01306 
01307 
01308 void MSILWriter::printFunctionBody(const Function& F) {
01309   // Print body
01310   for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
01311     if (Loop *L = LInfo->getLoopFor(I)) {
01312       if (L->getHeader()==I && L->getParentLoop()==0)
01313         printLoop(L);
01314     } else {
01315       printBasicBlock(I);
01316     }
01317   }
01318 }
01319 
01320 
01321 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
01322   const Value *left = 0, *right = 0;
01323   if (CE->getNumOperands()>=1) left = CE->getOperand(0);
01324   if (CE->getNumOperands()>=2) right = CE->getOperand(1);
01325   // Print instruction
01326   switch (CE->getOpcode()) {
01327   case Instruction::Trunc:
01328   case Instruction::ZExt:
01329   case Instruction::SExt:
01330   case Instruction::FPTrunc:
01331   case Instruction::FPExt:
01332   case Instruction::UIToFP:
01333   case Instruction::SIToFP:
01334   case Instruction::FPToUI:
01335   case Instruction::FPToSI:
01336   case Instruction::PtrToInt:
01337   case Instruction::IntToPtr:
01338   case Instruction::BitCast:
01339     printCastInstruction(CE->getOpcode(),left,CE->getType());
01340     break;
01341   case Instruction::GetElementPtr:
01342     printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
01343     break;
01344   case Instruction::ICmp:
01345     printICmpInstruction(CE->getPredicate(),left,right);
01346     break;
01347   case Instruction::FCmp:
01348     printFCmpInstruction(CE->getPredicate(),left,right);
01349     break;
01350   case Instruction::Select:
01351     printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
01352     break;
01353   case Instruction::Add:
01354   case Instruction::FAdd:
01355     printBinaryInstruction("add",left,right);
01356     break;
01357   case Instruction::Sub:
01358   case Instruction::FSub:
01359     printBinaryInstruction("sub",left,right);
01360     break;
01361   case Instruction::Mul:
01362   case Instruction::FMul:
01363     printBinaryInstruction("mul",left,right);
01364     break;
01365   case Instruction::UDiv:
01366     printBinaryInstruction("div.un",left,right);
01367     break;
01368   case Instruction::SDiv:
01369   case Instruction::FDiv:
01370     printBinaryInstruction("div",left,right);
01371     break;
01372   case Instruction::URem:
01373     printBinaryInstruction("rem.un",left,right);
01374     break;
01375   case Instruction::SRem:
01376   case Instruction::FRem:
01377     printBinaryInstruction("rem",left,right);
01378     break;
01379   case Instruction::And:
01380     printBinaryInstruction("and",left,right);
01381     break;
01382   case Instruction::Or:
01383     printBinaryInstruction("or",left,right);
01384     break;
01385   case Instruction::Xor:
01386     printBinaryInstruction("xor",left,right);
01387     break;
01388   case Instruction::Shl:
01389     printBinaryInstruction("shl",left,right);
01390     break;
01391   case Instruction::LShr:
01392     printBinaryInstruction("shr.un",left,right);
01393     break;
01394   case Instruction::AShr:
01395     printBinaryInstruction("shr",left,right);
01396     break;
01397   default:
01398     errs() << "Expression = " << *CE << "\n";
01399     llvm_unreachable("Invalid constant expression");
01400   }
01401 }
01402 
01403 
01404 void MSILWriter::printStaticInitializerList() {
01405   // List of global variables with uninitialized fields.
01406   for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
01407        VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
01408        ++VarI) {
01409     const std::vector<StaticInitializer>& InitList = VarI->second;
01410     if (InitList.empty()) continue;
01411     // For each uninitialized field.
01412     for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
01413          E = InitList.end(); I!=E; ++I) {
01414       if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
01415         // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
01416         //  utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
01417         // Load variable address
01418         printValueLoad(VarI->first);
01419         // Add offset
01420         if (I->offset!=0) {
01421           printPtrLoad(I->offset);
01422           printSimpleInstruction("add");
01423         }
01424         // Load value
01425         printConstantExpr(CE);
01426         // Save result at offset
01427         std::string postfix = getTypePostfix(CE->getType(),true);
01428         if (*postfix.begin()=='u') *postfix.begin() = 'i';
01429         postfix = "stind."+postfix;
01430         printSimpleInstruction(postfix.c_str());
01431       } else {
01432         errs() << "Constant = " << *I->constant << '\n';
01433         llvm_unreachable("Invalid static initializer");
01434       }
01435     }
01436   }
01437 }
01438 
01439 
01440 void MSILWriter::printFunction(const Function& F) {
01441   bool isSigned = F.paramHasAttr(0, Attribute::SExt);
01442   Out << "\n.method static ";
01443   Out << (F.hasLocalLinkage() ? "private " : "public ");
01444   if (F.isVarArg()) Out << "vararg ";
01445   Out << getTypeName(F.getReturnType(),isSigned) << 
01446     getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
01447   // Arguments
01448   Out << "\t(";
01449   unsigned ArgIdx = 1;
01450   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
01451        ++I, ++ArgIdx) {
01452     isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
01453     if (I!=F.arg_begin()) Out << ", ";
01454     Out << getTypeName(I->getType(),isSigned) << getValueName(I);
01455   }
01456   Out << ") cil managed\n";
01457   // Body
01458   Out << "{\n";
01459   printLocalVariables(F);
01460   printFunctionBody(F);
01461   Out << "}\n";
01462 }
01463 
01464 
01465 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
01466   std::string Name;
01467   std::set<const Type*> Printed;
01468   for (std::set<const Type*>::const_iterator
01469        UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
01470     const Type* Ty = *UI;
01471     if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
01472       Name = getTypeName(Ty, false, true);
01473     // Type with no need to declare.
01474     else continue;
01475     // Print not duplicated type
01476     if (Printed.insert(Ty).second) {
01477       Out << ".class value explicit ansi sealed '" << Name << "'";
01478       Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
01479       Out << " }\n\n";
01480     }
01481   }
01482 }
01483 
01484 
01485 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
01486   unsigned int N = Ty->getPrimitiveSizeInBits();
01487   assert(N!=0 && "Invalid type in getBitWidth()");
01488   switch (N) {
01489   case 1:
01490   case 8:
01491   case 16:
01492   case 32:
01493   case 64:
01494     return N;
01495   default:
01496     errs() << "Bits = " << N << '\n';
01497     llvm_unreachable("Unsupported integer width");
01498   }
01499   return 0; // Not reached
01500 }
01501 
01502 
01503 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
01504   uint64_t TySize = 0;
01505   const Type* Ty = C->getType();
01506   // Print zero initialized constant.
01507   if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
01508     TySize = TD->getTypeAllocSize(C->getType());
01509     Offset += TySize;
01510     Out << "int8 (0) [" << TySize << "]";
01511     return;
01512   }
01513   // Print constant initializer
01514   switch (Ty->getTypeID()) {
01515   case Type::IntegerTyID: {
01516     TySize = TD->getTypeAllocSize(Ty);
01517     const ConstantInt* Int = cast<ConstantInt>(C);
01518     Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
01519     break;
01520   }
01521   case Type::FloatTyID:
01522   case Type::DoubleTyID: {
01523     TySize = TD->getTypeAllocSize(Ty);
01524     const ConstantFP* FP = cast<ConstantFP>(C);
01525     if (Ty->getTypeID() == Type::FloatTyID)
01526       Out << "int32 (" << 
01527         (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
01528     else
01529       Out << "int64 (" << 
01530         FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
01531     break;
01532   }
01533   case Type::ArrayTyID:
01534   case Type::VectorTyID:
01535   case Type::StructTyID:
01536     for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
01537       if (I!=0) Out << ",\n";
01538       printStaticConstant(C->getOperand(I),Offset);
01539     }
01540     break;
01541   case Type::PointerTyID:
01542     TySize = TD->getTypeAllocSize(C->getType());
01543     // Initialize with global variable address
01544     if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
01545       std::string name = getValueName(G);
01546       Out << "&(" << name.insert(name.length()-1,"$data") << ")";
01547     } else {
01548       // Dynamic initialization
01549       if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
01550         InitListPtr->push_back(StaticInitializer(C,Offset));
01551       // Null pointer initialization
01552       if (TySize==4) Out << "int32 (0)";
01553       else if (TySize==8) Out << "int64 (0)";
01554       else llvm_unreachable("Invalid pointer size");
01555     }
01556     break;
01557   default:
01558     errs() << "TypeID = " << Ty->getTypeID() << '\n';
01559     llvm_unreachable("Invalid type in printStaticConstant()");
01560   }
01561   // Increase offset.
01562   Offset += TySize;
01563 }
01564 
01565 
01566 void MSILWriter::printStaticInitializer(const Constant* C,
01567                                         const std::string& Name) {
01568   switch (C->getType()->getTypeID()) {
01569   case Type::IntegerTyID:
01570   case Type::FloatTyID:
01571   case Type::DoubleTyID: 
01572     Out << getPrimitiveTypeName(C->getType(), false);
01573     break;
01574   case Type::ArrayTyID:
01575   case Type::VectorTyID:
01576   case Type::StructTyID:
01577   case Type::PointerTyID:
01578     Out << getTypeName(C->getType());
01579     break;
01580   default:
01581     errs() << "Type = " << *C << "\n";
01582     llvm_unreachable("Invalid constant type");
01583   }
01584   // Print initializer
01585   std::string label = Name;
01586   label.insert(label.length()-1,"$data");
01587   Out << Name << " at " << label << '\n';
01588   Out << ".data " << label << " = {\n";
01589   uint64_t offset = 0;
01590   printStaticConstant(C,offset);
01591   Out << "\n}\n\n";
01592 }
01593 
01594 
01595 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
01596   const Constant* C = G->getInitializer();
01597   if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
01598     InitListPtr = 0;
01599   else
01600     InitListPtr = &StaticInitList[G];
01601   printStaticInitializer(C,getValueName(G));
01602 }
01603 
01604 
01605 void MSILWriter::printGlobalVariables() {
01606   if (ModulePtr->global_empty()) return;
01607   Module::global_iterator I,E;
01608   for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
01609     // Variable definition
01610     Out << ".field static " << (I->isDeclaration() ? "public " :
01611                                                      "private ");
01612     if (I->isDeclaration()) {
01613       Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
01614     } else
01615       printVariableDefinition(&*I);
01616   }
01617 }
01618 
01619 
01620 const char* MSILWriter::getLibraryName(const Function* F) {
01621   return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
01622 }
01623 
01624 
01625 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
01626   return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
01627 }
01628 
01629 
01630 const char* MSILWriter::getLibraryForSymbol(const StringRef &Name, 
01631                                             bool isFunction,
01632                                             unsigned CallingConv) {
01633   // TODO: Read *.def file with function and libraries definitions.
01634   return "MSVCRT.DLL";  
01635 }
01636 
01637 
01638 void MSILWriter::printExternals() {
01639   Module::const_iterator I,E;
01640   // Functions.
01641   for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
01642     // Skip intrisics
01643     if (I->isIntrinsic()) continue;
01644     if (I->isDeclaration()) {
01645       const Function* F = I; 
01646       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
01647       std::string Sig = 
01648         getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
01649       Out << ".method static hidebysig pinvokeimpl(\""
01650           << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
01651     }
01652   }
01653   // External variables and static initialization.
01654   Out <<
01655   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
01656   "  native int LoadLibrary(string) preservesig {}\n"
01657   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
01658   "  native int GetProcAddress(native int, string) preservesig {}\n";
01659   Out <<
01660   ".method private static void* $MSIL_Import(string lib,string sym)\n"
01661   " managed cil\n{\n"
01662   "\tldarg\tlib\n"
01663   "\tcall\tnative int LoadLibrary(string)\n"
01664   "\tldarg\tsym\n"
01665   "\tcall\tnative int GetProcAddress(native int,string)\n"
01666   "\tdup\n"
01667   "\tbrtrue\tL_01\n"
01668   "\tldstr\t\"Can no import variable\"\n"
01669   "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
01670   "\tthrow\n"
01671   "L_01:\n"
01672   "\tret\n"
01673   "}\n\n"
01674   ".method static private void $MSIL_Init() managed cil\n{\n";
01675   printStaticInitializerList();
01676   // Foreach global variable.
01677   for (Module::global_iterator I = ModulePtr->global_begin(),
01678        E = ModulePtr->global_end(); I!=E; ++I) {
01679     if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
01680     // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
01681     std::string Label = "not_null$_"+utostr(getUniqID());
01682     std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
01683     printSimpleInstruction("ldsflda",Tmp.c_str());
01684     Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
01685     Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
01686     printSimpleInstruction("call","void* $MSIL_Import(string,string)");
01687     printIndirectSave(I->getType());
01688   }
01689   printSimpleInstruction("ret");
01690   Out << "}\n\n";
01691 }
01692 
01693 
01694 //===----------------------------------------------------------------------===//
01695 //                      External Interface declaration
01696 //===----------------------------------------------------------------------===//
01697 
01698 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
01699                                           formatted_raw_ostream &o,
01700                                           CodeGenFileType FileType,
01701                                           CodeGenOpt::Level OptLevel)
01702 {
01703   if (FileType != TargetMachine::AssemblyFile) return true;
01704   MSILWriter* Writer = new MSILWriter(o);
01705   PM.add(createGCLoweringPass());
01706   PM.add(createLowerAllocationsPass(true));
01707   // FIXME: Handle switch trougth native IL instruction "switch"
01708   PM.add(createLowerSwitchPass());
01709   PM.add(createCFGSimplificationPass());
01710   PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
01711   PM.add(Writer);
01712   PM.add(createGCInfoDeleter());
01713   return false;
01714 }