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