blob: 077145b321a2fdf34faf4a0477a5e10e51549c64 [file] [log] [blame]
Chris Lattner31c2ec32007-05-06 20:31:17 +00001//===-- MSILWriter.cpp - Library for converting LLVM code to MSIL ---------===//
Anton Korobeynikov099883f2007-03-21 21:38:25 +00002//
Bill Wendling85db3a92008-02-26 10:57:23 +00003// The LLVM Compiler Infrastructure
Anton Korobeynikov099883f2007-03-21 21:38:25 +00004//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00007//
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"
Anton Korobeynikovf13090c2007-05-06 20:13:33 +000023#include "llvm/Support/MathExtras.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000024#include "llvm/Transforms/Scalar.h"
25#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000026#include "llvm/CodeGen/Passes.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000027
28namespace {
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; }
Owen Andersoncb371882008-08-21 00:14:44 +000037 virtual bool addPassesToEmitWholeFile(PassManager &PM, raw_ostream &Out,
Anton Korobeynikov099883f2007-03-21 21:38:25 +000038 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
Oscar Fuentes92adc192008-11-15 21:36:30 +000047/// 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.
52extern "C" int MSILTargetMachineModule;
53int MSILTargetMachineModule = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000054
Dan Gohmanb8cab922008-10-14 20:25:08 +000055static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
Anton Korobeynikov099883f2007-03-21 21:38:25 +000056
57bool 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
Devang Patel19974732007-05-03 01:11:54 +000091char MSILModule::ID = 0;
92char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000093
94bool MSILWriter::runOnFunction(Function &F) {
95 if (F.isDeclaration()) return false;
96 LInfo = &getAnalysis<LoopInfo>();
97 printFunction(F);
98 return false;
99}
100
101
102bool MSILWriter::doInitialization(Module &M) {
103 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000104 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000105 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();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000113 Out << "// Startup code\n";
114 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000115 return false;
116}
117
118
119bool MSILWriter::doFinalization(Module &M) {
120 delete Mang;
121 return false;
122}
123
124
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000125void 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 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000181 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000182 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);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000211 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000212 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
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000224bool MSILWriter::isZeroValue(const Value* V) {
225 if (const Constant *C = dyn_cast<Constant>(V))
226 return C->isNullValue();
227 return false;
228}
229
230
231std::string MSILWriter::getValueName(const Value* V) {
232 // Name into the quotes allow control and space characters.
233 return "'"+Mang->getValueName(V)+"'";
234}
235
236
237std::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
249std::string MSILWriter::getLabelName(const Value* V) {
250 return getLabelName(Mang->getValueName(V));
251}
252
253
254std::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 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000268 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000269}
270
271
272std::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 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000290 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000291}
292
293
294std::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 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000314 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000315}
316
317
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000318std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
319 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000320 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:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000327 if (isNested)
328 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000329 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
330 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000331 if (isNested)
332 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000333 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
334 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000335 if (isNested)
336 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000337 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
338 default:
339 cerr << "Type = " << *Ty << '\n';
340 assert(0 && "Invalid type in getTypeName()");
341 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000342 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000343}
344
345
346MSILWriter::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))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000352 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000353 // Variable
354 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000355 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000356 // Constant
357 else if (isa<Constant>(V))
358 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
359 // Local variable
360 return LocalVT;
361}
362
363
364std::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:
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000381 return "i"+utostr(TD->getTypePaddedSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000382 default:
383 cerr << "TypeID = " << Ty->getTypeID() << '\n';
384 assert(0 && "Invalid type in TypeToPostfix()");
385 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000386 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000387}
388
389
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000390void 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
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000404void 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?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000409 if (!isUInt32(N)) {
410 cerr << "Value = " << utostr(N) << '\n';
411 assert(0 && "32-bit pointer overflowed");
412 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000413 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
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000423void MSILWriter::printValuePtrLoad(const Value* V) {
424 printValueLoad(V);
425 printConvToPtr();
426}
427
428
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000429void 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();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000437 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000438 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000439 uint64_t X;
440 unsigned Size;
441 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000442 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000443 Size = 4;
444 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000445 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000446 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);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000452 } else {
453 cerr << "Constant = " << *C << '\n';
454 assert(0 && "Invalid constant value");
455 }
456 Out << '\n';
457}
458
459
460void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000461 MSILWriter::ValueType Location = getValueLocation(V);
462 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000463 // 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 {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000471 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000472 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000473 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 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000480 }
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
508void 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
523void 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
531void 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
539void 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
551void 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
594void 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
605void 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
617void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000618 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000619 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000620 if (const PointerType* P = dyn_cast<PointerType>(Ty))
621 Ty = P->getElementType();
622 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000623 printSimpleInstruction(Tmp.c_str());
624}
625
626
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000627void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000628 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000629 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000630 printIndirectSave(Val->getType());
631}
632
633
634void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000635 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000636 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000637 if (*postfix.begin()=='u') *postfix.begin() = 'i';
638 postfix = "stind."+postfix;
639 printSimpleInstruction(postfix.c_str());
640}
641
642
643void 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
678void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
679 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000680 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000681 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000682 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000683 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000684 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)
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000691 Size += TD->getTypePaddedSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000692 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000693 printSimpleInstruction("add");
694 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000695 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000696 Size = TD->getTypePaddedSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000697 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000698 Size = TD->getTypePaddedSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000699 }
700 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000701 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);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000710 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000711 printPtrLoad(Size);
712 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000713 printSimpleInstruction("mul");
714 }
715 printSimpleInstruction("add");
716 }
717 }
718}
719
720
721std::string MSILWriter::getCallSignature(const FunctionType* Ty,
722 const Instruction* Inst,
723 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000724 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000725 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) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000737 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000738 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
754void MSILWriter::printFunctionCall(const Value* FnVal,
755 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000756 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000757 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 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000766 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000767 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000768 Name += getValueName(F);
769 printSimpleInstruction("call",
770 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
771 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000772 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000773 const PointerType* PTy = cast<PointerType>(FnVal->getType());
774 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000775 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000776 printValueLoad(FnVal);
777 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
778 }
779}
780
781
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000782void 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());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000797 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000798 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
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000817void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000818 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 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000827}
828
829
830void 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:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000837 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000838 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000839 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000840 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
880void 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);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000946 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000947 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
974void 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
996void 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
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001011void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1012 printIndirectLoad(Inst->getOperand(0));
1013 printSimpleInstruction("call",
1014 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1015 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001016 std::string Name =
1017 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001018 printSimpleInstruction(Name.c_str());
1019}
1020
1021
1022void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001023 uint64_t Size = TD->getTypePaddedSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001024 // 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
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001036void 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
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001041 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001042 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:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001096 printValueLoad(Left);
1097 printValueLoad(Right);
1098 printSimpleInstruction("conv.i4");
1099 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001100 break;
1101 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001102 printValueLoad(Left);
1103 printValueLoad(Right);
1104 printSimpleInstruction("conv.i4");
1105 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001106 break;
1107 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001108 printValueLoad(Left);
1109 printValueLoad(Right);
1110 printSimpleInstruction("conv.i4");
1111 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001112 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:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001120 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001121 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;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001147 case Instruction::Unwind:
1148 printSimpleInstruction("newobj",
1149 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001150 printSimpleInstruction("throw");
1151 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001152 case Instruction::Switch:
1153 printSwitchInstruction(cast<SwitchInst>(Inst));
1154 break;
1155 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001156 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001157 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:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001165 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1166 printSimpleInstruction("newobj",
1167 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001168 printSimpleInstruction("throw");
1169 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001170 case Instruction::VAArg:
1171 printVAArgInstruction(cast<VAArgInst>(Inst));
1172 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001173 default:
1174 cerr << "Instruction = " << Inst->getName() << '\n';
1175 assert(0 && "Unsupported instruction");
1176 }
1177}
1178
1179
1180void 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
1195void 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
Owen Andersoncb371882008-08-21 00:14:44 +00001200 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001201 // 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
1215void MSILWriter::printLocalVariables(const Function& F) {
1216 std::string Name;
1217 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001218 std::set<const Value*> Printed;
1219 const Value* VaList = NULL;
1220 unsigned StackDepth = 8;
1221 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001222 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001223 if (I->getOpcode()==Instruction::Call ||
1224 I->getOpcode()==Instruction::Invoke) {
1225 // Test stack depth.
1226 if (StackDepth<I->getNumOperands())
1227 StackDepth = I->getNumOperands();
1228 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001229 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1230 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001231 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001232 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001233 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001234 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001235 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001236 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001237 Ty = I->getType();
1238 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001239 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 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001267 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001268 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001269}
1270
1271
1272void 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
1285void 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
1365void 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)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001376 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1377 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001378 // 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
1401void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001402 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001403 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001404 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001405 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) {
Devang Patel05988662008-09-25 21:00:45 +00001413 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001414 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";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001420 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001421 printFunctionBody(F);
1422 Out << "}\n";
1423}
1424
1425
1426void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1427 std::string Name;
1428 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001429 for (std::set<const Type*>::const_iterator
1430 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1431 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001432 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1433 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001434 // 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 << "'";
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001439 Out << " { .pack " << 1 << " .size " << TD->getTypePaddedSize(Ty);
1440 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001441 }
1442 }
1443}
1444
1445
1446unsigned 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 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001460 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001461}
1462
1463
1464void 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()) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001469 TySize = TD->getTypePaddedSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001470 Offset += TySize;
1471 Out << "int8 (0) [" << TySize << "]";
1472 return;
1473 }
1474 // Print constant initializer
1475 switch (Ty->getTypeID()) {
1476 case Type::IntegerTyID: {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001477 TySize = TD->getTypePaddedSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001478 const ConstantInt* Int = cast<ConstantInt>(C);
1479 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1480 break;
1481 }
1482 case Type::FloatTyID:
1483 case Type::DoubleTyID: {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001484 TySize = TD->getTypePaddedSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001485 const ConstantFP* FP = cast<ConstantFP>(C);
1486 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001487 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001488 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001489 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001490 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001491 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001492 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:
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001503 TySize = TD->getTypePaddedSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001504 // 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
1527void 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:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001533 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001534 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
1556void 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
1566void 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
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001571 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);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001577 }
1578}
1579
1580
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001581const char* MSILWriter::getLibraryName(const Function* F) {
1582 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1583}
1584
1585
1586const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1587 return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1588}
1589
1590
1591const 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
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001598void MSILWriter::printExternals() {
1599 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001600 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001601 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1602 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001603 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001604 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001605 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001606 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001607 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";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001611 }
1612 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001613 // 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";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001651}
1652
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001653
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001654//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001655// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001656//===----------------------------------------------------------------------===//
1657
Owen Andersoncb371882008-08-21 00:14:44 +00001658bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001659 CodeGenFileType FileType, bool Fast)
1660{
1661 if (FileType != TargetMachine::AssemblyFile) return true;
1662 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001663 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001664 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);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001670 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001671 return false;
1672}