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