Introduce new headers whose inclusion forces linking and
[oota-llvm.git] / lib / Target / MSIL / MSILWriter.cpp
1 //===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library converts LLVM code to MSIL code.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
27
28 namespace {
29   // TargetMachine for the MSIL 
30   struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
31     const TargetData DataLayout;       // Calculates type size & alignment
32
33     MSILTarget(const Module &M, const std::string &FS)
34       : DataLayout(&M) {}
35
36     virtual bool WantsWholeFile() const { return true; }
37     virtual bool addPassesToEmitWholeFile(PassManager &PM, raw_ostream &Out,
38                                           CodeGenFileType FileType,
39                                           CodeGenOpt::Level OptLevel);
40
41     // This class always works, but shouldn't be the default in most cases.
42     static unsigned getModuleMatchQuality(const Module &M) { return 1; }
43
44     virtual const TargetData *getTargetData() const { return &DataLayout; }
45   };
46 }
47
48 /// MSILTargetMachineModule - Note that this is used on hosts that
49 /// cannot link in a library unless there are references into the
50 /// library.  In particular, it seems that it is not possible to get
51 /// things to work on Win32 without this.  Though it is unused, do not
52 /// remove it.
53 extern "C" int MSILTargetMachineModule;
54 int MSILTargetMachineModule = 0;
55
56 static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
57
58 // Force static initialization when called from llvm/InitializeAllTargets.h
59 namespace llvm {
60   void InitializeMSILTarget() { }
61 }
62
63 bool MSILModule::runOnModule(Module &M) {
64   ModulePtr = &M;
65   TD = &getAnalysis<TargetData>();
66   bool Changed = false;
67   // Find named types.  
68   TypeSymbolTable& Table = M.getTypeSymbolTable();
69   std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
70   for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
71     if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
72       Table.remove(I++);
73     else {
74       std::set<const Type *>::iterator T = Types.find(I->second);
75       if (T==Types.end())
76         Table.remove(I++);
77       else {
78         Types.erase(T);
79         ++I;
80       }
81     }
82   }
83   // Find unnamed types.
84   unsigned RenameCounter = 0;
85   for (std::set<const Type *>::const_iterator I = Types.begin(),
86        E = Types.end(); I!=E; ++I)
87     if (const StructType *STy = dyn_cast<StructType>(*I)) {
88       while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
89         ++RenameCounter;
90       Changed = true;
91     }
92   // Pointer for FunctionPass.
93   UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
94   return Changed;
95 }
96
97 char MSILModule::ID = 0;
98 char MSILWriter::ID = 0;
99
100 bool MSILWriter::runOnFunction(Function &F) {
101   if (F.isDeclaration()) return false;
102
103   // Do not codegen any 'available_externally' functions at all, they have
104   // definitions outside the translation unit.
105   if (F.hasAvailableExternallyLinkage())
106     return false;
107
108   LInfo = &getAnalysis<LoopInfo>();
109   printFunction(F);
110   return false;
111 }
112
113
114 bool MSILWriter::doInitialization(Module &M) {
115   ModulePtr = &M;
116   Mang = new Mangler(M);
117   Out << ".assembly extern mscorlib {}\n";
118   Out << ".assembly MSIL {}\n\n";
119   Out << "// External\n";
120   printExternals();
121   Out << "// Declarations\n";
122   printDeclarations(M.getTypeSymbolTable());
123   Out << "// Definitions\n";
124   printGlobalVariables();
125   Out << "// Startup code\n";
126   printModuleStartup();
127   return false;
128 }
129
130
131 bool MSILWriter::doFinalization(Module &M) {
132   delete Mang;
133   return false;
134 }
135
136
137 void MSILWriter::printModuleStartup() {
138   Out <<
139   ".method static public int32 $MSIL_Startup() {\n"
140   "\t.entrypoint\n"
141   "\t.locals (native int i)\n"
142   "\t.locals (native int argc)\n"
143   "\t.locals (native int ptr)\n"
144   "\t.locals (void* argv)\n"
145   "\t.locals (string[] args)\n"
146   "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
147   "\tdup\n"
148   "\tstloc\targs\n"
149   "\tldlen\n"
150   "\tconv.i4\n"
151   "\tdup\n"
152   "\tstloc\targc\n";
153   printPtrLoad(TD->getPointerSize());
154   Out <<
155   "\tmul\n"
156   "\tlocalloc\n"
157   "\tstloc\targv\n"
158   "\tldc.i4.0\n"
159   "\tstloc\ti\n"
160   "L_01:\n"
161   "\tldloc\ti\n"
162   "\tldloc\targc\n"
163   "\tceq\n"
164   "\tbrtrue\tL_02\n"
165   "\tldloc\targs\n"
166   "\tldloc\ti\n"
167   "\tldelem.ref\n"
168   "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
169            "StringToHGlobalAnsi(string)\n"
170   "\tstloc\tptr\n"
171   "\tldloc\targv\n"
172   "\tldloc\ti\n";
173   printPtrLoad(TD->getPointerSize());
174   Out << 
175   "\tmul\n"
176   "\tadd\n"
177   "\tldloc\tptr\n"
178   "\tstind.i\n"
179   "\tldloc\ti\n"
180   "\tldc.i4.1\n"
181   "\tadd\n"
182   "\tstloc\ti\n"
183   "\tbr\tL_01\n"
184   "L_02:\n"
185   "\tcall void $MSIL_Init()\n";
186
187   // Call user 'main' function.
188   const Function* F = ModulePtr->getFunction("main");
189   if (!F || F->isDeclaration()) {
190     Out << "\tldc.i4.0\n\tret\n}\n";
191     return;
192   }
193   bool BadSig = true;
194   std::string Args("");
195   Function::const_arg_iterator Arg1,Arg2;
196
197   switch (F->arg_size()) {
198   case 0:
199     BadSig = false;
200     break;
201   case 1:
202     Arg1 = F->arg_begin();
203     if (Arg1->getType()->isInteger()) {
204       Out << "\tldloc\targc\n";
205       Args = getTypeName(Arg1->getType());
206       BadSig = false;
207     }
208     break;
209   case 2:
210     Arg1 = Arg2 = F->arg_begin(); ++Arg2;
211     if (Arg1->getType()->isInteger() && 
212         Arg2->getType()->getTypeID() == Type::PointerTyID) {
213       Out << "\tldloc\targc\n\tldloc\targv\n";
214       Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
215       BadSig = false;
216     }
217     break;
218   default:
219     BadSig = true;
220   }
221
222   bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
223   if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
224     Out << "\tldc.i4.0\n";
225   } else {
226     Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
227       getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
228     if (RetVoid)
229       Out << "\tldc.i4.0\n";
230     else
231       Out << "\tconv.i4\n";
232   }
233   Out << "\tret\n}\n";
234 }
235
236 bool MSILWriter::isZeroValue(const Value* V) {
237   if (const Constant *C = dyn_cast<Constant>(V))
238     return C->isNullValue();
239   return false;
240 }
241
242
243 std::string MSILWriter::getValueName(const Value* V) {
244   // Name into the quotes allow control and space characters.
245   return "'"+Mang->getValueName(V)+"'";
246 }
247
248
249 std::string MSILWriter::getLabelName(const std::string& Name) {
250   if (Name.find('.')!=std::string::npos) {
251     std::string Tmp(Name);
252     // Replace unaccepable characters in the label name.
253     for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
254       if (*I=='.') *I = '@';
255     return Tmp;
256   }
257   return Name;
258 }
259
260
261 std::string MSILWriter::getLabelName(const Value* V) {
262   return getLabelName(Mang->getValueName(V));
263 }
264
265
266 std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
267   switch (CallingConvID) {
268   case CallingConv::C:
269   case CallingConv::Cold:
270   case CallingConv::Fast:
271     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
272   case CallingConv::X86_FastCall:
273     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
274   case CallingConv::X86_StdCall:
275     return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
276   default:
277     cerr << "CallingConvID = " << CallingConvID << '\n';
278     assert(0 && "Unsupported calling convention");
279   }
280   return ""; // Not reached
281 }
282
283
284 std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
285   std::string Tmp = "";
286   const Type* ElemTy = Ty;
287   assert(Ty->getTypeID()==TyID && "Invalid type passed");
288   // Walk trought array element types.
289   for (;;) {
290     // Multidimensional array.
291     if (ElemTy->getTypeID()==TyID) {
292       if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
293         Tmp += utostr(ATy->getNumElements());
294       else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
295         Tmp += utostr(VTy->getNumElements());
296       ElemTy = cast<SequentialType>(ElemTy)->getElementType();
297     }
298     // Base element type found.
299     if (ElemTy->getTypeID()!=TyID) break;
300     Tmp += ",";
301   }
302   return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
303 }
304
305
306 std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
307   unsigned NumBits = 0;
308   switch (Ty->getTypeID()) {
309   case Type::VoidTyID:
310     return "void ";
311   case Type::IntegerTyID:
312     NumBits = getBitWidth(Ty);
313     if(NumBits==1)
314       return "bool ";
315     if (!isSigned)
316       return "unsigned int"+utostr(NumBits)+" ";
317     return "int"+utostr(NumBits)+" ";
318   case Type::FloatTyID:
319     return "float32 ";
320   case Type::DoubleTyID:
321     return "float64 "; 
322   default:
323     cerr << "Type = " << *Ty << '\n';
324     assert(0 && "Invalid primitive type");
325   }
326   return ""; // Not reached
327 }
328
329
330 std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
331                                     bool isNested) {
332   if (Ty->isPrimitiveType() || Ty->isInteger())
333     return getPrimitiveTypeName(Ty,isSigned);
334   // FIXME: "OpaqueType" support
335   switch (Ty->getTypeID()) {
336   case Type::PointerTyID:
337     return "void* ";
338   case Type::StructTyID:
339     if (isNested)
340       return ModulePtr->getTypeName(Ty);
341     return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
342   case Type::ArrayTyID:
343     if (isNested)
344       return getArrayTypeName(Ty->getTypeID(),Ty);
345     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
346   case Type::VectorTyID:
347     if (isNested)
348       return getArrayTypeName(Ty->getTypeID(),Ty);
349     return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
350   default:
351     cerr << "Type = " << *Ty << '\n';
352     assert(0 && "Invalid type in getTypeName()");
353   }
354   return ""; // Not reached
355 }
356
357
358 MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
359   // Function argument
360   if (isa<Argument>(V))
361     return ArgumentVT;
362   // Function
363   else if (const Function* F = dyn_cast<Function>(V))
364     return F->hasLocalLinkage() ? InternalVT : GlobalVT;
365   // Variable
366   else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
367     return G->hasLocalLinkage() ? InternalVT : GlobalVT;
368   // Constant
369   else if (isa<Constant>(V))
370     return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
371   // Local variable
372   return LocalVT;
373 }
374
375
376 std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
377                                        bool isSigned) {
378   unsigned NumBits = 0;
379   switch (Ty->getTypeID()) {
380   // Integer constant, expanding for stack operations.
381   case Type::IntegerTyID:
382     NumBits = getBitWidth(Ty);
383     // Expand integer value to "int32" or "int64".
384     if (Expand) return (NumBits<=32 ? "i4" : "i8");
385     if (NumBits==1) return "i1";
386     return (isSigned ? "i" : "u")+utostr(NumBits/8);
387   // Float constant.
388   case Type::FloatTyID:
389     return "r4";
390   case Type::DoubleTyID:
391     return "r8";
392   case Type::PointerTyID:
393     return "i"+utostr(TD->getTypeAllocSize(Ty));
394   default:
395     cerr << "TypeID = " << Ty->getTypeID() << '\n';
396     assert(0 && "Invalid type in TypeToPostfix()");
397   }
398   return ""; // Not reached
399 }
400
401
402 void MSILWriter::printConvToPtr() {
403   switch (ModulePtr->getPointerSize()) {
404   case Module::Pointer32:
405     printSimpleInstruction("conv.u4");
406     break;
407   case Module::Pointer64:
408     printSimpleInstruction("conv.u8");
409     break;
410   default:
411     assert(0 && "Module use not supporting pointer size");
412   }
413 }
414
415
416 void MSILWriter::printPtrLoad(uint64_t N) {
417   switch (ModulePtr->getPointerSize()) {
418   case Module::Pointer32:
419     printSimpleInstruction("ldc.i4",utostr(N).c_str());
420     // FIXME: Need overflow test?
421     if (!isUInt32(N)) {
422       cerr << "Value = " << utostr(N) << '\n';
423       assert(0 && "32-bit pointer overflowed");
424     }
425     break;
426   case Module::Pointer64:
427     printSimpleInstruction("ldc.i8",utostr(N).c_str());
428     break;
429   default:
430     assert(0 && "Module use not supporting pointer size");
431   }
432 }
433
434
435 void MSILWriter::printValuePtrLoad(const Value* V) {
436   printValueLoad(V);
437   printConvToPtr();
438 }
439
440
441 void MSILWriter::printConstLoad(const Constant* C) {
442   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
443     // Integer constant
444     Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
445     if (CInt->isMinValue(true))
446       Out << CInt->getSExtValue();
447     else
448       Out << CInt->getZExtValue();
449   } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
450     // Float constant
451     uint64_t X;
452     unsigned Size;
453     if (FP->getType()->getTypeID()==Type::FloatTyID) {
454       X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
455       Size = 4;  
456     } else {
457       X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
458       Size = 8;  
459     }
460     Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
461   } else if (isa<UndefValue>(C)) {
462     // Undefined constant value = NULL.
463     printPtrLoad(0);
464   } else {
465     cerr << "Constant = " << *C << '\n';
466     assert(0 && "Invalid constant value");
467   }
468   Out << '\n';
469 }
470
471
472 void MSILWriter::printValueLoad(const Value* V) {
473   MSILWriter::ValueType Location = getValueLocation(V);
474   switch (Location) {
475   // Global variable or function address.
476   case GlobalVT:
477   case InternalVT:
478     if (const Function* F = dyn_cast<Function>(V)) {
479       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
480       printSimpleInstruction("ldftn",
481         getCallSignature(F->getFunctionType(),NULL,Name).c_str());
482     } else {
483       std::string Tmp;
484       const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
485       if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
486         Tmp = "void* "+getValueName(V);
487         printSimpleInstruction("ldsfld",Tmp.c_str());
488       } else {
489         Tmp = getTypeName(ElemTy)+getValueName(V);
490         printSimpleInstruction("ldsflda",Tmp.c_str());
491       }
492     }
493     break;
494   // Function argument.
495   case ArgumentVT:
496     printSimpleInstruction("ldarg",getValueName(V).c_str());
497     break;
498   // Local function variable.
499   case LocalVT:
500     printSimpleInstruction("ldloc",getValueName(V).c_str());
501     break;
502   // Constant value.
503   case ConstVT:
504     if (isa<ConstantPointerNull>(V))
505       printPtrLoad(0);
506     else
507       printConstLoad(cast<Constant>(V));
508     break;
509   // Constant expression.
510   case ConstExprVT:
511     printConstantExpr(cast<ConstantExpr>(V));
512     break;
513   default:
514     cerr << "Value = " << *V << '\n';
515     assert(0 && "Invalid value location");
516   }
517 }
518
519
520 void MSILWriter::printValueSave(const Value* V) {
521   switch (getValueLocation(V)) {
522   case ArgumentVT:
523     printSimpleInstruction("starg",getValueName(V).c_str());
524     break;
525   case LocalVT:
526     printSimpleInstruction("stloc",getValueName(V).c_str());
527     break;
528   default:
529     cerr << "Value  = " << *V << '\n';
530     assert(0 && "Invalid value location");
531   }
532 }
533
534
535 void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
536                                         const Value* Right) {
537   printValueLoad(Left);
538   printValueLoad(Right);
539   Out << '\t' << Name << '\n';
540 }
541
542
543 void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
544   if(Operand) 
545     Out << '\t' << Inst << '\t' << Operand << '\n';
546   else
547     Out << '\t' << Inst << '\n';
548 }
549
550
551 void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
552   for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
553        isa<PHINode>(I); ++I) {
554     const PHINode* Phi = cast<PHINode>(I);
555     const Value* Val = Phi->getIncomingValueForBlock(Src);
556     if (isa<UndefValue>(Val)) continue;
557     printValueLoad(Val);
558     printValueSave(Phi);
559   }
560 }
561
562
563 void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
564                                     const BasicBlock* TrueBB,
565                                     const BasicBlock* FalseBB) {
566   if (TrueBB==FalseBB) {
567     // "TrueBB" and "FalseBB" destination equals
568     printPHICopy(CurrBB,TrueBB);
569     printSimpleInstruction("pop");
570     printSimpleInstruction("br",getLabelName(TrueBB).c_str());
571   } else if (FalseBB==NULL) {
572     // If "FalseBB" not used the jump have condition
573     printPHICopy(CurrBB,TrueBB);
574     printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
575   } else if (TrueBB==NULL) {
576     // If "TrueBB" not used the jump is unconditional
577     printPHICopy(CurrBB,FalseBB);
578     printSimpleInstruction("br",getLabelName(FalseBB).c_str());
579   } else {
580     // Copy PHI instructions for each block
581     std::string TmpLabel;
582     // Print PHI instructions for "TrueBB"
583     if (isa<PHINode>(TrueBB->begin())) {
584       TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
585       printSimpleInstruction("brtrue",TmpLabel.c_str());
586     } else {
587       printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
588     }
589     // Print PHI instructions for "FalseBB"
590     if (isa<PHINode>(FalseBB->begin())) {
591       printPHICopy(CurrBB,FalseBB);
592       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
593     } else {
594       printSimpleInstruction("br",getLabelName(FalseBB).c_str());
595     }
596     if (isa<PHINode>(TrueBB->begin())) {
597       // Handle "TrueBB" PHI Copy
598       Out << TmpLabel << ":\n";
599       printPHICopy(CurrBB,TrueBB);
600       printSimpleInstruction("br",getLabelName(TrueBB).c_str());
601     }
602   }
603 }
604
605
606 void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
607   if (Inst->isUnconditional()) {
608     printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
609   } else {
610     printValueLoad(Inst->getCondition());
611     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
612                        Inst->getSuccessor(1));
613   }
614 }
615
616
617 void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
618                                         const Value* VFalse) {
619   std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
620   printValueLoad(VTrue);
621   printValueLoad(Cond);
622   printSimpleInstruction("brtrue",TmpLabel.c_str());
623   printSimpleInstruction("pop");
624   printValueLoad(VFalse);
625   Out << TmpLabel << ":\n";
626 }
627
628
629 void MSILWriter::printIndirectLoad(const Value* V) {
630   const Type* Ty = V->getType();
631   printValueLoad(V);
632   if (const PointerType* P = dyn_cast<PointerType>(Ty))
633     Ty = P->getElementType();
634   std::string Tmp = "ldind."+getTypePostfix(Ty, false);
635   printSimpleInstruction(Tmp.c_str());
636 }
637
638
639 void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
640   printValueLoad(Ptr);
641   printValueLoad(Val);
642   printIndirectSave(Val->getType());
643 }
644
645
646 void MSILWriter::printIndirectSave(const Type* Ty) {
647   // Instruction need signed postfix for any type.
648   std::string postfix = getTypePostfix(Ty, false);
649   if (*postfix.begin()=='u') *postfix.begin() = 'i';
650   postfix = "stind."+postfix;
651   printSimpleInstruction(postfix.c_str());
652 }
653
654
655 void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
656                                       const Type* Ty) {
657   std::string Tmp("");
658   printValueLoad(V);
659   switch (Op) {
660   // Signed
661   case Instruction::SExt:
662   case Instruction::SIToFP:
663   case Instruction::FPToSI:
664     Tmp = "conv."+getTypePostfix(Ty,false,true);
665     printSimpleInstruction(Tmp.c_str());
666     break;
667   // Unsigned
668   case Instruction::FPTrunc:
669   case Instruction::FPExt:
670   case Instruction::UIToFP:
671   case Instruction::Trunc:
672   case Instruction::ZExt:
673   case Instruction::FPToUI:
674   case Instruction::PtrToInt:
675   case Instruction::IntToPtr:
676     Tmp = "conv."+getTypePostfix(Ty,false);
677     printSimpleInstruction(Tmp.c_str());
678     break;
679   // Do nothing
680   case Instruction::BitCast:
681     // FIXME: meaning that ld*/st* instruction do not change data format.
682     break;
683   default:
684     cerr << "Opcode = " << Op << '\n';
685     assert(0 && "Invalid conversion instruction");
686   }
687 }
688
689
690 void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
691                                      gep_type_iterator E) {
692   unsigned Size;
693   // Load address
694   printValuePtrLoad(V);
695   // Calculate element offset.
696   for (; I!=E; ++I){
697     Size = 0;
698     const Value* IndexValue = I.getOperand();
699     if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
700       uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
701       // Offset is the sum of all previous structure fields.
702       for (uint64_t F = 0; F<FieldIndex; ++F)
703         Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
704       printPtrLoad(Size);
705       printSimpleInstruction("add");
706       continue;
707     } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
708       Size = TD->getTypeAllocSize(SeqTy->getElementType());
709     } else {
710       Size = TD->getTypeAllocSize(*I);
711     }
712     // Add offset of current element to stack top.
713     if (!isZeroValue(IndexValue)) {
714       // Constant optimization.
715       if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
716         if (C->getValue().isNegative()) {
717           printPtrLoad(C->getValue().abs().getZExtValue()*Size);
718           printSimpleInstruction("sub");
719           continue;
720         } else
721           printPtrLoad(C->getZExtValue()*Size);
722       } else {
723         printPtrLoad(Size);
724         printValuePtrLoad(IndexValue);
725         printSimpleInstruction("mul");
726       }
727       printSimpleInstruction("add");
728     }
729   }
730 }
731
732
733 std::string MSILWriter::getCallSignature(const FunctionType* Ty,
734                                          const Instruction* Inst,
735                                          std::string Name) {
736   std::string Tmp("");
737   if (Ty->isVarArg()) Tmp += "vararg ";
738   // Name and return type.
739   Tmp += getTypeName(Ty->getReturnType())+Name+"(";
740   // Function argument type list.
741   unsigned NumParams = Ty->getNumParams();
742   for (unsigned I = 0; I!=NumParams; ++I) {
743     if (I!=0) Tmp += ",";
744     Tmp += getTypeName(Ty->getParamType(I));
745   }
746   // CLR needs to know the exact amount of parameters received by vararg
747   // function, because caller cleans the stack.
748   if (Ty->isVarArg() && Inst) {
749     // Origin to function arguments in "CallInst" or "InvokeInst".
750     unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
751     // Print variable argument types.
752     unsigned NumOperands = Inst->getNumOperands()-Org;
753     if (NumParams<NumOperands) {
754       if (NumParams!=0) Tmp += ", ";
755       Tmp += "... , ";
756       for (unsigned J = NumParams; J!=NumOperands; ++J) {
757         if (J!=NumParams) Tmp += ", ";
758         Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
759       }
760     }
761   }
762   return Tmp+")";
763 }
764
765
766 void MSILWriter::printFunctionCall(const Value* FnVal,
767                                    const Instruction* Inst) {
768   // Get function calling convention.
769   std::string Name = "";
770   if (const CallInst* Call = dyn_cast<CallInst>(Inst))
771     Name = getConvModopt(Call->getCallingConv());
772   else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
773     Name = getConvModopt(Invoke->getCallingConv());
774   else {
775     cerr << "Instruction = " << Inst->getName() << '\n';
776     assert(0 && "Need \"Invoke\" or \"Call\" instruction only");
777   }
778   if (const Function* F = dyn_cast<Function>(FnVal)) {
779     // Direct call.
780     Name += getValueName(F);
781     printSimpleInstruction("call",
782       getCallSignature(F->getFunctionType(),Inst,Name).c_str());
783   } else {
784     // Indirect function call.
785     const PointerType* PTy = cast<PointerType>(FnVal->getType());
786     const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
787     // Load function address.
788     printValueLoad(FnVal);
789     printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
790   }
791 }
792
793
794 void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
795   std::string Name;
796   switch (Inst->getIntrinsicID()) {
797   case Intrinsic::vastart:
798     Name = getValueName(Inst->getOperand(1));
799     Name.insert(Name.length()-1,"$valist");
800     // Obtain the argument handle.
801     printSimpleInstruction("ldloca",Name.c_str());
802     printSimpleInstruction("arglist");
803     printSimpleInstruction("call",
804       "instance void [mscorlib]System.ArgIterator::.ctor"
805       "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
806     // Save as pointer type "void*"
807     printValueLoad(Inst->getOperand(1));
808     printSimpleInstruction("ldloca",Name.c_str());
809     printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
810     break;
811   case Intrinsic::vaend:
812     // Close argument list handle.
813     printIndirectLoad(Inst->getOperand(1));
814     printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
815     break;
816   case Intrinsic::vacopy:
817     // Copy "ArgIterator" valuetype.
818     printIndirectLoad(Inst->getOperand(1));
819     printIndirectLoad(Inst->getOperand(2));
820     printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
821     break;        
822   default:
823     cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
824     assert(0 && "Invalid intrinsic function");
825   }
826 }
827
828
829 void MSILWriter::printCallInstruction(const Instruction* Inst) {
830   if (isa<IntrinsicInst>(Inst)) {
831     // Handle intrinsic function.
832     printIntrinsicCall(cast<IntrinsicInst>(Inst));
833   } else {
834     // Load arguments to stack and call function.
835     for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
836       printValueLoad(Inst->getOperand(I));
837     printFunctionCall(Inst->getOperand(0),Inst);
838   }
839 }
840
841
842 void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
843                                       const Value* Right) {
844   switch (Predicate) {
845   case ICmpInst::ICMP_EQ:
846     printBinaryInstruction("ceq",Left,Right);
847     break;
848   case ICmpInst::ICMP_NE:
849     // Emulate = not neg (Op1 eq Op2)
850     printBinaryInstruction("ceq",Left,Right);
851     printSimpleInstruction("neg");
852     printSimpleInstruction("not");
853     break;
854   case ICmpInst::ICMP_ULE:
855   case ICmpInst::ICMP_SLE:
856     // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
857     printBinaryInstruction("ceq",Left,Right);
858     if (Predicate==ICmpInst::ICMP_ULE)
859       printBinaryInstruction("clt.un",Left,Right);
860     else
861       printBinaryInstruction("clt",Left,Right);
862     printSimpleInstruction("or");
863     break;
864   case ICmpInst::ICMP_UGE:
865   case ICmpInst::ICMP_SGE:
866     // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
867     printBinaryInstruction("ceq",Left,Right);
868     if (Predicate==ICmpInst::ICMP_UGE)
869       printBinaryInstruction("cgt.un",Left,Right);
870     else
871       printBinaryInstruction("cgt",Left,Right);
872     printSimpleInstruction("or");
873     break;
874   case ICmpInst::ICMP_ULT:
875     printBinaryInstruction("clt.un",Left,Right);
876     break;
877   case ICmpInst::ICMP_SLT:
878     printBinaryInstruction("clt",Left,Right);
879     break;
880   case ICmpInst::ICMP_UGT:
881     printBinaryInstruction("cgt.un",Left,Right);
882   case ICmpInst::ICMP_SGT:
883     printBinaryInstruction("cgt",Left,Right);
884     break;
885   default:
886     cerr << "Predicate = " << Predicate << '\n';
887     assert(0 && "Invalid icmp predicate");
888   }
889 }
890
891
892 void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
893                                       const Value* Right) {
894   // FIXME: Correct comparison
895   std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
896   switch (Predicate) {
897   case FCmpInst::FCMP_UGT:
898     // X >  Y || llvm_fcmp_uno(X, Y)
899     printBinaryInstruction("cgt",Left,Right);
900     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
901     printSimpleInstruction("or");
902     break;
903   case FCmpInst::FCMP_OGT:
904     // X >  Y
905     printBinaryInstruction("cgt",Left,Right);
906     break;
907   case FCmpInst::FCMP_UGE:
908     // X >= Y || llvm_fcmp_uno(X, Y)
909     printBinaryInstruction("ceq",Left,Right);
910     printBinaryInstruction("cgt",Left,Right);
911     printSimpleInstruction("or");
912     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
913     printSimpleInstruction("or");
914     break;
915   case FCmpInst::FCMP_OGE:
916     // X >= Y
917     printBinaryInstruction("ceq",Left,Right);
918     printBinaryInstruction("cgt",Left,Right);
919     printSimpleInstruction("or");
920     break;
921   case FCmpInst::FCMP_ULT:
922     // X <  Y || llvm_fcmp_uno(X, Y)
923     printBinaryInstruction("clt",Left,Right);
924     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
925     printSimpleInstruction("or");
926     break;
927   case FCmpInst::FCMP_OLT:
928     // X <  Y
929     printBinaryInstruction("clt",Left,Right);
930     break;
931   case FCmpInst::FCMP_ULE:
932     // X <= Y || llvm_fcmp_uno(X, Y)
933     printBinaryInstruction("ceq",Left,Right);
934     printBinaryInstruction("clt",Left,Right);
935     printSimpleInstruction("or");
936     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
937     printSimpleInstruction("or");
938     break;
939   case FCmpInst::FCMP_OLE:
940     // X <= Y
941     printBinaryInstruction("ceq",Left,Right);
942     printBinaryInstruction("clt",Left,Right);
943     printSimpleInstruction("or");
944     break;
945   case FCmpInst::FCMP_UEQ:
946     // X == Y || llvm_fcmp_uno(X, Y)
947     printBinaryInstruction("ceq",Left,Right);
948     printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
949     printSimpleInstruction("or");
950     break;
951   case FCmpInst::FCMP_OEQ:
952     // X == Y
953     printBinaryInstruction("ceq",Left,Right);
954     break;
955   case FCmpInst::FCMP_UNE:
956     // X != Y
957     printBinaryInstruction("ceq",Left,Right);
958     printSimpleInstruction("neg");
959     printSimpleInstruction("not");
960     break;
961   case FCmpInst::FCMP_ONE:
962     // X != Y && llvm_fcmp_ord(X, Y)
963     printBinaryInstruction("ceq",Left,Right);
964     printSimpleInstruction("not");
965     break;
966   case FCmpInst::FCMP_ORD:
967     // return X == X && Y == Y
968     printBinaryInstruction("ceq",Left,Left);
969     printBinaryInstruction("ceq",Right,Right);
970     printSimpleInstruction("or");
971     break;
972   case FCmpInst::FCMP_UNO:
973     // X != X || Y != Y
974     printBinaryInstruction("ceq",Left,Left);
975     printSimpleInstruction("not");
976     printBinaryInstruction("ceq",Right,Right);
977     printSimpleInstruction("not");
978     printSimpleInstruction("or");
979     break;
980   default:
981     assert(0 && "Illegal FCmp predicate");
982   }
983 }
984
985
986 void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
987   std::string Label = "leave$normal_"+utostr(getUniqID());
988   Out << ".try {\n";
989   // Load arguments
990   for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
991     printValueLoad(Inst->getOperand(I));
992   // Print call instruction
993   printFunctionCall(Inst->getOperand(0),Inst);
994   // Save function result and leave "try" block
995   printValueSave(Inst);
996   printSimpleInstruction("leave",Label.c_str());
997   Out << "}\n";
998   Out << "catch [mscorlib]System.Exception {\n";
999   // Redirect to unwind block
1000   printSimpleInstruction("pop");
1001   printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1002   Out << "}\n" << Label << ":\n";
1003   // Redirect to continue block
1004   printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1005 }
1006
1007
1008 void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1009   // FIXME: Emulate with IL "switch" instruction
1010   // Emulate = if () else if () else if () else ...
1011   for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1012     printValueLoad(Inst->getCondition());
1013     printValueLoad(Inst->getCaseValue(I));
1014     printSimpleInstruction("ceq");
1015     // Condition jump to successor block
1016     printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1017   }
1018   // Jump to default block
1019   printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1020 }
1021
1022
1023 void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1024   printIndirectLoad(Inst->getOperand(0));
1025   printSimpleInstruction("call",
1026     "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1027   printSimpleInstruction("refanyval","void*");
1028   std::string Name = 
1029     "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
1030   printSimpleInstruction(Name.c_str());
1031 }
1032
1033
1034 void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
1035   uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
1036   // Constant optimization.
1037   if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1038     printPtrLoad(CInt->getZExtValue()*Size);
1039   } else {
1040     printPtrLoad(Size);
1041     printValueLoad(Inst->getOperand(0));
1042     printSimpleInstruction("mul");
1043   }
1044   printSimpleInstruction("localloc");
1045 }
1046
1047
1048 void MSILWriter::printInstruction(const Instruction* Inst) {
1049   const Value *Left = 0, *Right = 0;
1050   if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1051   if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1052   // Print instruction
1053   // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
1054   switch (Inst->getOpcode()) {
1055   // Terminator
1056   case Instruction::Ret:
1057     if (Inst->getNumOperands()) {
1058       printValueLoad(Left);
1059       printSimpleInstruction("ret");
1060     } else
1061       printSimpleInstruction("ret");
1062     break;
1063   case Instruction::Br:
1064     printBranchInstruction(cast<BranchInst>(Inst));
1065     break;
1066   // Binary
1067   case Instruction::Add:
1068   case Instruction::FAdd:
1069     printBinaryInstruction("add",Left,Right);
1070     break;
1071   case Instruction::Sub:
1072   case Instruction::FSub:
1073     printBinaryInstruction("sub",Left,Right);
1074     break;
1075   case Instruction::Mul:
1076   case Instruction::FMul:
1077     printBinaryInstruction("mul",Left,Right);
1078     break;
1079   case Instruction::UDiv:
1080     printBinaryInstruction("div.un",Left,Right);
1081     break;
1082   case Instruction::SDiv:
1083   case Instruction::FDiv:
1084     printBinaryInstruction("div",Left,Right);
1085     break;
1086   case Instruction::URem:
1087     printBinaryInstruction("rem.un",Left,Right);
1088     break;
1089   case Instruction::SRem:
1090   case Instruction::FRem:
1091     printBinaryInstruction("rem",Left,Right);
1092     break;
1093   // Binary Condition
1094   case Instruction::ICmp:
1095     printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1096     break;
1097   case Instruction::FCmp:
1098     printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1099     break;
1100   // Bitwise Binary
1101   case Instruction::And:
1102     printBinaryInstruction("and",Left,Right);
1103     break;
1104   case Instruction::Or:
1105     printBinaryInstruction("or",Left,Right);
1106     break;
1107   case Instruction::Xor:
1108     printBinaryInstruction("xor",Left,Right);
1109     break;
1110   case Instruction::Shl:
1111     printValueLoad(Left);
1112     printValueLoad(Right);
1113     printSimpleInstruction("conv.i4");
1114     printSimpleInstruction("shl");
1115     break;
1116   case Instruction::LShr:
1117     printValueLoad(Left);
1118     printValueLoad(Right);
1119     printSimpleInstruction("conv.i4");
1120     printSimpleInstruction("shr.un");
1121     break;
1122   case Instruction::AShr:
1123     printValueLoad(Left);
1124     printValueLoad(Right);
1125     printSimpleInstruction("conv.i4");
1126     printSimpleInstruction("shr");
1127     break;
1128   case Instruction::Select:
1129     printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1130     break;
1131   case Instruction::Load:
1132     printIndirectLoad(Inst->getOperand(0));
1133     break;
1134   case Instruction::Store:
1135     printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
1136     break;
1137   case Instruction::Trunc:
1138   case Instruction::ZExt:
1139   case Instruction::SExt:
1140   case Instruction::FPTrunc:
1141   case Instruction::FPExt:
1142   case Instruction::UIToFP:
1143   case Instruction::SIToFP:
1144   case Instruction::FPToUI:
1145   case Instruction::FPToSI:
1146   case Instruction::PtrToInt:
1147   case Instruction::IntToPtr:
1148   case Instruction::BitCast:
1149     printCastInstruction(Inst->getOpcode(),Left,
1150                          cast<CastInst>(Inst)->getDestTy());
1151     break;
1152   case Instruction::GetElementPtr:
1153     printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1154                         gep_type_end(Inst));
1155     break;
1156   case Instruction::Call:
1157     printCallInstruction(cast<CallInst>(Inst));
1158     break;
1159   case Instruction::Invoke:
1160     printInvokeInstruction(cast<InvokeInst>(Inst));
1161     break;
1162   case Instruction::Unwind:
1163     printSimpleInstruction("newobj",
1164       "instance void [mscorlib]System.Exception::.ctor()");
1165     printSimpleInstruction("throw");
1166     break;
1167   case Instruction::Switch:
1168     printSwitchInstruction(cast<SwitchInst>(Inst));
1169     break;
1170   case Instruction::Alloca:
1171     printAllocaInstruction(cast<AllocaInst>(Inst));
1172     break;
1173   case Instruction::Malloc:
1174     assert(0 && "LowerAllocationsPass used");
1175     break;
1176   case Instruction::Free:
1177     assert(0 && "LowerAllocationsPass used");
1178     break;
1179   case Instruction::Unreachable:
1180     printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1181     printSimpleInstruction("newobj",
1182       "instance void [mscorlib]System.Exception::.ctor(string)");
1183     printSimpleInstruction("throw");
1184     break;
1185   case Instruction::VAArg:
1186     printVAArgInstruction(cast<VAArgInst>(Inst));
1187     break;
1188   default:
1189     cerr << "Instruction = " << Inst->getName() << '\n';
1190     assert(0 && "Unsupported instruction");
1191   }
1192 }
1193
1194
1195 void MSILWriter::printLoop(const Loop* L) {
1196   Out << getLabelName(L->getHeader()->getName()) << ":\n";
1197   const std::vector<BasicBlock*>& blocks = L->getBlocks();
1198   for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1199     BasicBlock* BB = blocks[I];
1200     Loop* BBLoop = LInfo->getLoopFor(BB);
1201     if (BBLoop == L)
1202       printBasicBlock(BB);
1203     else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1204       printLoop(BBLoop);
1205   }
1206   printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1207 }
1208
1209
1210 void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1211   Out << getLabelName(BB) << ":\n";
1212   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1213     const Instruction* Inst = I;
1214     // Comment llvm original instruction
1215     // Out << "\n//" << *Inst << "\n";
1216     // Do not handle PHI instruction in current block
1217     if (Inst->getOpcode()==Instruction::PHI) continue;
1218     // Print instruction
1219     printInstruction(Inst);
1220     // Save result
1221     if (Inst->getType()!=Type::VoidTy) {
1222       // Do not save value after invoke, it done in "try" block
1223       if (Inst->getOpcode()==Instruction::Invoke) continue;
1224       printValueSave(Inst);
1225     }
1226   }
1227 }
1228
1229
1230 void MSILWriter::printLocalVariables(const Function& F) {
1231   std::string Name;
1232   const Type* Ty = NULL;
1233   std::set<const Value*> Printed;
1234   const Value* VaList = NULL;
1235   unsigned StackDepth = 8;
1236   // Find local variables
1237   for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
1238     if (I->getOpcode()==Instruction::Call ||
1239         I->getOpcode()==Instruction::Invoke) {
1240       // Test stack depth.
1241       if (StackDepth<I->getNumOperands())
1242         StackDepth = I->getNumOperands();
1243     }
1244     const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1245     if (AI && !isa<GlobalVariable>(AI)) {
1246       // Local variable allocation.
1247       Ty = PointerType::getUnqual(AI->getAllocatedType());
1248       Name = getValueName(AI);
1249       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1250     } else if (I->getType()!=Type::VoidTy) {
1251       // Operation result.
1252       Ty = I->getType();
1253       Name = getValueName(&*I);
1254       Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1255     }
1256     // Test on 'va_list' variable    
1257     bool isVaList = false;     
1258     if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1259       // "va_list" as "va_arg" instruction operand.
1260       isVaList = true;
1261       VaList = VaInst->getOperand(0);
1262     } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1263       // "va_list" as intrinsic function operand. 
1264       switch (Inst->getIntrinsicID()) {
1265       case Intrinsic::vastart:
1266       case Intrinsic::vaend:
1267       case Intrinsic::vacopy:
1268         isVaList = true;
1269         VaList = Inst->getOperand(1);
1270         break;
1271       default:
1272         isVaList = false;
1273       }
1274     }
1275     // Print "va_list" variable.
1276     if (isVaList && Printed.insert(VaList).second) {
1277       Name = getValueName(VaList);
1278       Name.insert(Name.length()-1,"$valist");
1279       Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1280           << Name << ")\n";
1281     }
1282   }
1283   printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
1284 }
1285
1286
1287 void MSILWriter::printFunctionBody(const Function& F) {
1288   // Print body
1289   for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1290     if (Loop *L = LInfo->getLoopFor(I)) {
1291       if (L->getHeader()==I && L->getParentLoop()==0)
1292         printLoop(L);
1293     } else {
1294       printBasicBlock(I);
1295     }
1296   }
1297 }
1298
1299
1300 void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1301   const Value *left = 0, *right = 0;
1302   if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1303   if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1304   // Print instruction
1305   switch (CE->getOpcode()) {
1306   case Instruction::Trunc:
1307   case Instruction::ZExt:
1308   case Instruction::SExt:
1309   case Instruction::FPTrunc:
1310   case Instruction::FPExt:
1311   case Instruction::UIToFP:
1312   case Instruction::SIToFP:
1313   case Instruction::FPToUI:
1314   case Instruction::FPToSI:
1315   case Instruction::PtrToInt:
1316   case Instruction::IntToPtr:
1317   case Instruction::BitCast:
1318     printCastInstruction(CE->getOpcode(),left,CE->getType());
1319     break;
1320   case Instruction::GetElementPtr:
1321     printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1322     break;
1323   case Instruction::ICmp:
1324     printICmpInstruction(CE->getPredicate(),left,right);
1325     break;
1326   case Instruction::FCmp:
1327     printFCmpInstruction(CE->getPredicate(),left,right);
1328     break;
1329   case Instruction::Select:
1330     printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1331     break;
1332   case Instruction::Add:
1333   case Instruction::FAdd:
1334     printBinaryInstruction("add",left,right);
1335     break;
1336   case Instruction::Sub:
1337   case Instruction::FSub:
1338     printBinaryInstruction("sub",left,right);
1339     break;
1340   case Instruction::Mul:
1341   case Instruction::FMul:
1342     printBinaryInstruction("mul",left,right);
1343     break;
1344   case Instruction::UDiv:
1345     printBinaryInstruction("div.un",left,right);
1346     break;
1347   case Instruction::SDiv:
1348   case Instruction::FDiv:
1349     printBinaryInstruction("div",left,right);
1350     break;
1351   case Instruction::URem:
1352     printBinaryInstruction("rem.un",left,right);
1353     break;
1354   case Instruction::SRem:
1355   case Instruction::FRem:
1356     printBinaryInstruction("rem",left,right);
1357     break;
1358   case Instruction::And:
1359     printBinaryInstruction("and",left,right);
1360     break;
1361   case Instruction::Or:
1362     printBinaryInstruction("or",left,right);
1363     break;
1364   case Instruction::Xor:
1365     printBinaryInstruction("xor",left,right);
1366     break;
1367   case Instruction::Shl:
1368     printBinaryInstruction("shl",left,right);
1369     break;
1370   case Instruction::LShr:
1371     printBinaryInstruction("shr.un",left,right);
1372     break;
1373   case Instruction::AShr:
1374     printBinaryInstruction("shr",left,right);
1375     break;
1376   default:
1377     cerr << "Expression = " << *CE << "\n";
1378     assert(0 && "Invalid constant expression");
1379   }
1380 }
1381
1382
1383 void MSILWriter::printStaticInitializerList() {
1384   // List of global variables with uninitialized fields.
1385   for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1386        VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1387        ++VarI) {
1388     const std::vector<StaticInitializer>& InitList = VarI->second;
1389     if (InitList.empty()) continue;
1390     // For each uninitialized field.
1391     for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1392          E = InitList.end(); I!=E; ++I) {
1393       if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
1394         // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1395         //  utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
1396         // Load variable address
1397         printValueLoad(VarI->first);
1398         // Add offset
1399         if (I->offset!=0) {
1400           printPtrLoad(I->offset);
1401           printSimpleInstruction("add");
1402         }
1403         // Load value
1404         printConstantExpr(CE);
1405         // Save result at offset
1406         std::string postfix = getTypePostfix(CE->getType(),true);
1407         if (*postfix.begin()=='u') *postfix.begin() = 'i';
1408         postfix = "stind."+postfix;
1409         printSimpleInstruction(postfix.c_str());
1410       } else {
1411         cerr << "Constant = " << *I->constant << '\n';
1412         assert(0 && "Invalid static initializer");
1413       }
1414     }
1415   }
1416 }
1417
1418
1419 void MSILWriter::printFunction(const Function& F) {
1420   bool isSigned = F.paramHasAttr(0, Attribute::SExt);
1421   Out << "\n.method static ";
1422   Out << (F.hasLocalLinkage() ? "private " : "public ");
1423   if (F.isVarArg()) Out << "vararg ";
1424   Out << getTypeName(F.getReturnType(),isSigned) << 
1425     getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1426   // Arguments
1427   Out << "\t(";
1428   unsigned ArgIdx = 1;
1429   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1430        ++I, ++ArgIdx) {
1431     isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
1432     if (I!=F.arg_begin()) Out << ", ";
1433     Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1434   }
1435   Out << ") cil managed\n";
1436   // Body
1437   Out << "{\n";
1438   printLocalVariables(F);
1439   printFunctionBody(F);
1440   Out << "}\n";
1441 }
1442
1443
1444 void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1445   std::string Name;
1446   std::set<const Type*> Printed;
1447   for (std::set<const Type*>::const_iterator
1448        UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1449     const Type* Ty = *UI;
1450     if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1451       Name = getTypeName(Ty, false, true);
1452     // Type with no need to declare.
1453     else continue;
1454     // Print not duplicated type
1455     if (Printed.insert(Ty).second) {
1456       Out << ".class value explicit ansi sealed '" << Name << "'";
1457       Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
1458       Out << " }\n\n";
1459     }
1460   }
1461 }
1462
1463
1464 unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1465   unsigned int N = Ty->getPrimitiveSizeInBits();
1466   assert(N!=0 && "Invalid type in getBitWidth()");
1467   switch (N) {
1468   case 1:
1469   case 8:
1470   case 16:
1471   case 32:
1472   case 64:
1473     return N;
1474   default:
1475     cerr << "Bits = " << N << '\n';
1476     assert(0 && "Unsupported integer width");
1477   }
1478   return 0; // Not reached
1479 }
1480
1481
1482 void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1483   uint64_t TySize = 0;
1484   const Type* Ty = C->getType();
1485   // Print zero initialized constant.
1486   if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
1487     TySize = TD->getTypeAllocSize(C->getType());
1488     Offset += TySize;
1489     Out << "int8 (0) [" << TySize << "]";
1490     return;
1491   }
1492   // Print constant initializer
1493   switch (Ty->getTypeID()) {
1494   case Type::IntegerTyID: {
1495     TySize = TD->getTypeAllocSize(Ty);
1496     const ConstantInt* Int = cast<ConstantInt>(C);
1497     Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1498     break;
1499   }
1500   case Type::FloatTyID:
1501   case Type::DoubleTyID: {
1502     TySize = TD->getTypeAllocSize(Ty);
1503     const ConstantFP* FP = cast<ConstantFP>(C);
1504     if (Ty->getTypeID() == Type::FloatTyID)
1505       Out << "int32 (" << 
1506         (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1507     else
1508       Out << "int64 (" << 
1509         FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
1510     break;
1511   }
1512   case Type::ArrayTyID:
1513   case Type::VectorTyID:
1514   case Type::StructTyID:
1515     for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1516       if (I!=0) Out << ",\n";
1517       printStaticConstant(C->getOperand(I),Offset);
1518     }
1519     break;
1520   case Type::PointerTyID:
1521     TySize = TD->getTypeAllocSize(C->getType());
1522     // Initialize with global variable address
1523     if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1524       std::string name = getValueName(G);
1525       Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1526     } else {
1527       // Dynamic initialization
1528       if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1529         InitListPtr->push_back(StaticInitializer(C,Offset));
1530       // Null pointer initialization
1531       if (TySize==4) Out << "int32 (0)";
1532       else if (TySize==8) Out << "int64 (0)";
1533       else assert(0 && "Invalid pointer size");
1534     }
1535     break;
1536   default:
1537     cerr << "TypeID = " << Ty->getTypeID() << '\n';
1538     assert(0 && "Invalid type in printStaticConstant()");
1539   }
1540   // Increase offset.
1541   Offset += TySize;
1542 }
1543
1544
1545 void MSILWriter::printStaticInitializer(const Constant* C,
1546                                         const std::string& Name) {
1547   switch (C->getType()->getTypeID()) {
1548   case Type::IntegerTyID:
1549   case Type::FloatTyID:
1550   case Type::DoubleTyID: 
1551     Out << getPrimitiveTypeName(C->getType(), false);
1552     break;
1553   case Type::ArrayTyID:
1554   case Type::VectorTyID:
1555   case Type::StructTyID:
1556   case Type::PointerTyID:
1557     Out << getTypeName(C->getType());
1558     break;
1559   default:
1560     cerr << "Type = " << *C << "\n";
1561     assert(0 && "Invalid constant type");
1562   }
1563   // Print initializer
1564   std::string label = Name;
1565   label.insert(label.length()-1,"$data");
1566   Out << Name << " at " << label << '\n';
1567   Out << ".data " << label << " = {\n";
1568   uint64_t offset = 0;
1569   printStaticConstant(C,offset);
1570   Out << "\n}\n\n";
1571 }
1572
1573
1574 void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1575   const Constant* C = G->getInitializer();
1576   if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1577     InitListPtr = 0;
1578   else
1579     InitListPtr = &StaticInitList[G];
1580   printStaticInitializer(C,getValueName(G));
1581 }
1582
1583
1584 void MSILWriter::printGlobalVariables() {
1585   if (ModulePtr->global_empty()) return;
1586   Module::global_iterator I,E;
1587   for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1588     // Variable definition
1589     Out << ".field static " << (I->isDeclaration() ? "public " :
1590                                                      "private ");
1591     if (I->isDeclaration()) {
1592       Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1593     } else
1594       printVariableDefinition(&*I);
1595   }
1596 }
1597
1598
1599 const char* MSILWriter::getLibraryName(const Function* F) {
1600   return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1601 }
1602
1603
1604 const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1605   return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1606 }
1607
1608
1609 const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1610                                            unsigned CallingConv) {
1611   // TODO: Read *.def file with function and libraries definitions.
1612   return "MSVCRT.DLL";  
1613 }
1614
1615
1616 void MSILWriter::printExternals() {
1617   Module::const_iterator I,E;
1618   // Functions.
1619   for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1620     // Skip intrisics
1621     if (I->isIntrinsic()) continue;
1622     if (I->isDeclaration()) {
1623       const Function* F = I; 
1624       std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
1625       std::string Sig = 
1626         getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1627       Out << ".method static hidebysig pinvokeimpl(\""
1628           << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
1629     }
1630   }
1631   // External variables and static initialization.
1632   Out <<
1633   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1634   "  native int LoadLibrary(string) preservesig {}\n"
1635   ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1636   "  native int GetProcAddress(native int, string) preservesig {}\n";
1637   Out <<
1638   ".method private static void* $MSIL_Import(string lib,string sym)\n"
1639   " managed cil\n{\n"
1640   "\tldarg\tlib\n"
1641   "\tcall\tnative int LoadLibrary(string)\n"
1642   "\tldarg\tsym\n"
1643   "\tcall\tnative int GetProcAddress(native int,string)\n"
1644   "\tdup\n"
1645   "\tbrtrue\tL_01\n"
1646   "\tldstr\t\"Can no import variable\"\n"
1647   "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1648   "\tthrow\n"
1649   "L_01:\n"
1650   "\tret\n"
1651   "}\n\n"
1652   ".method static private void $MSIL_Init() managed cil\n{\n";
1653   printStaticInitializerList();
1654   // Foreach global variable.
1655   for (Module::global_iterator I = ModulePtr->global_begin(),
1656        E = ModulePtr->global_end(); I!=E; ++I) {
1657     if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1658     // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1659     std::string Label = "not_null$_"+utostr(getUniqID());
1660     std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1661     printSimpleInstruction("ldsflda",Tmp.c_str());
1662     Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1663     Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1664     printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1665     printIndirectSave(I->getType());
1666   }
1667   printSimpleInstruction("ret");
1668   Out << "}\n\n";
1669 }
1670
1671
1672 //===----------------------------------------------------------------------===//
1673 //                      External Interface declaration
1674 //===----------------------------------------------------------------------===//
1675
1676 bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
1677                                           CodeGenFileType FileType,
1678                                           CodeGenOpt::Level OptLevel)
1679 {
1680   if (FileType != TargetMachine::AssemblyFile) return true;
1681   MSILWriter* Writer = new MSILWriter(o);
1682   PM.add(createGCLoweringPass());
1683   PM.add(createLowerAllocationsPass(true));
1684   // FIXME: Handle switch trougth native IL instruction "switch"
1685   PM.add(createLowerSwitchPass());
1686   PM.add(createCFGSimplificationPass());
1687   PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1688   PM.add(Writer);
1689   PM.add(createGCInfoDeleter());
1690   return false;
1691 }