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