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