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