blob: 8429c27eb6bb761399a91055f114e89408240179 [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"
Torok Edwinc25e7582009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000023#include "llvm/Support/InstVisitor.h"
Anton Korobeynikovf13090c2007-05-06 20:13:33 +000024#include "llvm/Support/MathExtras.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000025#include "llvm/Transforms/Scalar.h"
26#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000027#include "llvm/CodeGen/Passes.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000028
29namespace {
30 // TargetMachine for the MSIL
31 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
32 const TargetData DataLayout; // Calculates type size & alignment
33
34 MSILTarget(const Module &M, const std::string &FS)
35 : DataLayout(&M) {}
36
37 virtual bool WantsWholeFile() const { return true; }
Owen Andersoncb371882008-08-21 00:14:44 +000038 virtual bool addPassesToEmitWholeFile(PassManager &PM, raw_ostream &Out,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000039 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +000040 CodeGenOpt::Level OptLevel);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000041
42 // This class always works, but shouldn't be the default in most cases.
43 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
44
45 virtual const TargetData *getTargetData() const { return &DataLayout; }
46 };
47}
48
Oscar Fuentes92adc192008-11-15 21:36:30 +000049/// MSILTargetMachineModule - Note that this is used on hosts that
50/// cannot link in a library unless there are references into the
51/// library. In particular, it seems that it is not possible to get
52/// things to work on Win32 without this. Though it is unused, do not
53/// remove it.
54extern "C" int MSILTargetMachineModule;
55int MSILTargetMachineModule = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000056
Dan Gohmanb8cab922008-10-14 20:25:08 +000057static RegisterTarget<MSILTarget> X("msil", "MSIL backend");
Anton Korobeynikov099883f2007-03-21 21:38:25 +000058
Bob Wilsona96751f2009-06-23 23:59:40 +000059// Force static initialization.
60extern "C" void LLVMInitializeMSILTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000061
Anton Korobeynikov099883f2007-03-21 21:38:25 +000062bool MSILModule::runOnModule(Module &M) {
63 ModulePtr = &M;
64 TD = &getAnalysis<TargetData>();
65 bool Changed = false;
66 // Find named types.
67 TypeSymbolTable& Table = M.getTypeSymbolTable();
68 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
69 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
70 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
71 Table.remove(I++);
72 else {
73 std::set<const Type *>::iterator T = Types.find(I->second);
74 if (T==Types.end())
75 Table.remove(I++);
76 else {
77 Types.erase(T);
78 ++I;
79 }
80 }
81 }
82 // Find unnamed types.
83 unsigned RenameCounter = 0;
84 for (std::set<const Type *>::const_iterator I = Types.begin(),
85 E = Types.end(); I!=E; ++I)
86 if (const StructType *STy = dyn_cast<StructType>(*I)) {
87 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
88 ++RenameCounter;
89 Changed = true;
90 }
91 // Pointer for FunctionPass.
92 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
93 return Changed;
94}
95
Devang Patel19974732007-05-03 01:11:54 +000096char MSILModule::ID = 0;
97char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000098
99bool MSILWriter::runOnFunction(Function &F) {
100 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +0000101
102 // Do not codegen any 'available_externally' functions at all, they have
103 // definitions outside the translation unit.
104 if (F.hasAvailableExternallyLinkage())
105 return false;
106
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000107 LInfo = &getAnalysis<LoopInfo>();
108 printFunction(F);
109 return false;
110}
111
112
113bool MSILWriter::doInitialization(Module &M) {
114 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000115 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000116 Out << ".assembly extern mscorlib {}\n";
117 Out << ".assembly MSIL {}\n\n";
118 Out << "// External\n";
119 printExternals();
120 Out << "// Declarations\n";
121 printDeclarations(M.getTypeSymbolTable());
122 Out << "// Definitions\n";
123 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000124 Out << "// Startup code\n";
125 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000126 return false;
127}
128
129
130bool MSILWriter::doFinalization(Module &M) {
131 delete Mang;
132 return false;
133}
134
135
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000136void MSILWriter::printModuleStartup() {
137 Out <<
138 ".method static public int32 $MSIL_Startup() {\n"
139 "\t.entrypoint\n"
140 "\t.locals (native int i)\n"
141 "\t.locals (native int argc)\n"
142 "\t.locals (native int ptr)\n"
143 "\t.locals (void* argv)\n"
144 "\t.locals (string[] args)\n"
145 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
146 "\tdup\n"
147 "\tstloc\targs\n"
148 "\tldlen\n"
149 "\tconv.i4\n"
150 "\tdup\n"
151 "\tstloc\targc\n";
152 printPtrLoad(TD->getPointerSize());
153 Out <<
154 "\tmul\n"
155 "\tlocalloc\n"
156 "\tstloc\targv\n"
157 "\tldc.i4.0\n"
158 "\tstloc\ti\n"
159 "L_01:\n"
160 "\tldloc\ti\n"
161 "\tldloc\targc\n"
162 "\tceq\n"
163 "\tbrtrue\tL_02\n"
164 "\tldloc\targs\n"
165 "\tldloc\ti\n"
166 "\tldelem.ref\n"
167 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
168 "StringToHGlobalAnsi(string)\n"
169 "\tstloc\tptr\n"
170 "\tldloc\targv\n"
171 "\tldloc\ti\n";
172 printPtrLoad(TD->getPointerSize());
173 Out <<
174 "\tmul\n"
175 "\tadd\n"
176 "\tldloc\tptr\n"
177 "\tstind.i\n"
178 "\tldloc\ti\n"
179 "\tldc.i4.1\n"
180 "\tadd\n"
181 "\tstloc\ti\n"
182 "\tbr\tL_01\n"
183 "L_02:\n"
184 "\tcall void $MSIL_Init()\n";
185
186 // Call user 'main' function.
187 const Function* F = ModulePtr->getFunction("main");
188 if (!F || F->isDeclaration()) {
189 Out << "\tldc.i4.0\n\tret\n}\n";
190 return;
191 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000192 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000193 std::string Args("");
194 Function::const_arg_iterator Arg1,Arg2;
195
196 switch (F->arg_size()) {
197 case 0:
198 BadSig = false;
199 break;
200 case 1:
201 Arg1 = F->arg_begin();
202 if (Arg1->getType()->isInteger()) {
203 Out << "\tldloc\targc\n";
204 Args = getTypeName(Arg1->getType());
205 BadSig = false;
206 }
207 break;
208 case 2:
209 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
210 if (Arg1->getType()->isInteger() &&
211 Arg2->getType()->getTypeID() == Type::PointerTyID) {
212 Out << "\tldloc\targc\n\tldloc\targv\n";
213 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
214 BadSig = false;
215 }
216 break;
217 default:
218 BadSig = true;
219 }
220
221 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000222 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000223 Out << "\tldc.i4.0\n";
224 } else {
225 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
226 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
227 if (RetVoid)
228 Out << "\tldc.i4.0\n";
229 else
230 Out << "\tconv.i4\n";
231 }
232 Out << "\tret\n}\n";
233}
234
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000235bool MSILWriter::isZeroValue(const Value* V) {
236 if (const Constant *C = dyn_cast<Constant>(V))
237 return C->isNullValue();
238 return false;
239}
240
241
242std::string MSILWriter::getValueName(const Value* V) {
243 // Name into the quotes allow control and space characters.
244 return "'"+Mang->getValueName(V)+"'";
245}
246
247
248std::string MSILWriter::getLabelName(const std::string& Name) {
249 if (Name.find('.')!=std::string::npos) {
250 std::string Tmp(Name);
251 // Replace unaccepable characters in the label name.
252 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
253 if (*I=='.') *I = '@';
254 return Tmp;
255 }
256 return Name;
257}
258
259
260std::string MSILWriter::getLabelName(const Value* V) {
261 return getLabelName(Mang->getValueName(V));
262}
263
264
265std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
266 switch (CallingConvID) {
267 case CallingConv::C:
268 case CallingConv::Cold:
269 case CallingConv::Fast:
270 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
271 case CallingConv::X86_FastCall:
272 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
273 case CallingConv::X86_StdCall:
274 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
275 default:
276 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000277 LLVM_UNREACHABLE("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000278 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000279 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000280}
281
282
283std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
284 std::string Tmp = "";
285 const Type* ElemTy = Ty;
286 assert(Ty->getTypeID()==TyID && "Invalid type passed");
287 // Walk trought array element types.
288 for (;;) {
289 // Multidimensional array.
290 if (ElemTy->getTypeID()==TyID) {
291 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
292 Tmp += utostr(ATy->getNumElements());
293 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
294 Tmp += utostr(VTy->getNumElements());
295 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
296 }
297 // Base element type found.
298 if (ElemTy->getTypeID()!=TyID) break;
299 Tmp += ",";
300 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000301 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000302}
303
304
305std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
306 unsigned NumBits = 0;
307 switch (Ty->getTypeID()) {
308 case Type::VoidTyID:
309 return "void ";
310 case Type::IntegerTyID:
311 NumBits = getBitWidth(Ty);
312 if(NumBits==1)
313 return "bool ";
314 if (!isSigned)
315 return "unsigned int"+utostr(NumBits)+" ";
316 return "int"+utostr(NumBits)+" ";
317 case Type::FloatTyID:
318 return "float32 ";
319 case Type::DoubleTyID:
320 return "float64 ";
321 default:
322 cerr << "Type = " << *Ty << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000323 LLVM_UNREACHABLE("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000324 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000325 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000326}
327
328
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000329std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
330 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000331 if (Ty->isPrimitiveType() || Ty->isInteger())
332 return getPrimitiveTypeName(Ty,isSigned);
333 // FIXME: "OpaqueType" support
334 switch (Ty->getTypeID()) {
335 case Type::PointerTyID:
336 return "void* ";
337 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000338 if (isNested)
339 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000340 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
341 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000342 if (isNested)
343 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000344 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
345 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000346 if (isNested)
347 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000348 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
349 default:
350 cerr << "Type = " << *Ty << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000351 LLVM_UNREACHABLE("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000352 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000353 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000354}
355
356
357MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
358 // Function argument
359 if (isa<Argument>(V))
360 return ArgumentVT;
361 // Function
362 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000363 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000364 // Variable
365 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000366 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000367 // Constant
368 else if (isa<Constant>(V))
369 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
370 // Local variable
371 return LocalVT;
372}
373
374
375std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
376 bool isSigned) {
377 unsigned NumBits = 0;
378 switch (Ty->getTypeID()) {
379 // Integer constant, expanding for stack operations.
380 case Type::IntegerTyID:
381 NumBits = getBitWidth(Ty);
382 // Expand integer value to "int32" or "int64".
383 if (Expand) return (NumBits<=32 ? "i4" : "i8");
384 if (NumBits==1) return "i1";
385 return (isSigned ? "i" : "u")+utostr(NumBits/8);
386 // Float constant.
387 case Type::FloatTyID:
388 return "r4";
389 case Type::DoubleTyID:
390 return "r8";
391 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000392 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000393 default:
394 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000395 LLVM_UNREACHABLE("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000396 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000397 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000398}
399
400
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000401void MSILWriter::printConvToPtr() {
402 switch (ModulePtr->getPointerSize()) {
403 case Module::Pointer32:
404 printSimpleInstruction("conv.u4");
405 break;
406 case Module::Pointer64:
407 printSimpleInstruction("conv.u8");
408 break;
409 default:
Torok Edwinc25e7582009-07-11 20:10:48 +0000410 LLVM_UNREACHABLE("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000411 }
412}
413
414
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000415void MSILWriter::printPtrLoad(uint64_t N) {
416 switch (ModulePtr->getPointerSize()) {
417 case Module::Pointer32:
418 printSimpleInstruction("ldc.i4",utostr(N).c_str());
419 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000420 if (!isUInt32(N)) {
421 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000422 LLVM_UNREACHABLE("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000423 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000424 break;
425 case Module::Pointer64:
426 printSimpleInstruction("ldc.i8",utostr(N).c_str());
427 break;
428 default:
Torok Edwinc25e7582009-07-11 20:10:48 +0000429 LLVM_UNREACHABLE("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000430 }
431}
432
433
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000434void MSILWriter::printValuePtrLoad(const Value* V) {
435 printValueLoad(V);
436 printConvToPtr();
437}
438
439
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000440void MSILWriter::printConstLoad(const Constant* C) {
441 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
442 // Integer constant
443 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
444 if (CInt->isMinValue(true))
445 Out << CInt->getSExtValue();
446 else
447 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000448 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000449 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000450 uint64_t X;
451 unsigned Size;
452 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000453 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000454 Size = 4;
455 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000456 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000457 Size = 8;
458 }
459 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
460 } else if (isa<UndefValue>(C)) {
461 // Undefined constant value = NULL.
462 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000463 } else {
464 cerr << "Constant = " << *C << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000465 LLVM_UNREACHABLE("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000466 }
467 Out << '\n';
468}
469
470
471void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000472 MSILWriter::ValueType Location = getValueLocation(V);
473 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000474 // Global variable or function address.
475 case GlobalVT:
476 case InternalVT:
477 if (const Function* F = dyn_cast<Function>(V)) {
478 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
479 printSimpleInstruction("ldftn",
480 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
481 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000482 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000483 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000484 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
485 Tmp = "void* "+getValueName(V);
486 printSimpleInstruction("ldsfld",Tmp.c_str());
487 } else {
488 Tmp = getTypeName(ElemTy)+getValueName(V);
489 printSimpleInstruction("ldsflda",Tmp.c_str());
490 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000491 }
492 break;
493 // Function argument.
494 case ArgumentVT:
495 printSimpleInstruction("ldarg",getValueName(V).c_str());
496 break;
497 // Local function variable.
498 case LocalVT:
499 printSimpleInstruction("ldloc",getValueName(V).c_str());
500 break;
501 // Constant value.
502 case ConstVT:
503 if (isa<ConstantPointerNull>(V))
504 printPtrLoad(0);
505 else
506 printConstLoad(cast<Constant>(V));
507 break;
508 // Constant expression.
509 case ConstExprVT:
510 printConstantExpr(cast<ConstantExpr>(V));
511 break;
512 default:
513 cerr << "Value = " << *V << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000514 LLVM_UNREACHABLE("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000515 }
516}
517
518
519void MSILWriter::printValueSave(const Value* V) {
520 switch (getValueLocation(V)) {
521 case ArgumentVT:
522 printSimpleInstruction("starg",getValueName(V).c_str());
523 break;
524 case LocalVT:
525 printSimpleInstruction("stloc",getValueName(V).c_str());
526 break;
527 default:
528 cerr << "Value = " << *V << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000529 LLVM_UNREACHABLE("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000530 }
531}
532
533
534void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
535 const Value* Right) {
536 printValueLoad(Left);
537 printValueLoad(Right);
538 Out << '\t' << Name << '\n';
539}
540
541
542void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
543 if(Operand)
544 Out << '\t' << Inst << '\t' << Operand << '\n';
545 else
546 Out << '\t' << Inst << '\n';
547}
548
549
550void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
551 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
552 isa<PHINode>(I); ++I) {
553 const PHINode* Phi = cast<PHINode>(I);
554 const Value* Val = Phi->getIncomingValueForBlock(Src);
555 if (isa<UndefValue>(Val)) continue;
556 printValueLoad(Val);
557 printValueSave(Phi);
558 }
559}
560
561
562void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
563 const BasicBlock* TrueBB,
564 const BasicBlock* FalseBB) {
565 if (TrueBB==FalseBB) {
566 // "TrueBB" and "FalseBB" destination equals
567 printPHICopy(CurrBB,TrueBB);
568 printSimpleInstruction("pop");
569 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
570 } else if (FalseBB==NULL) {
571 // If "FalseBB" not used the jump have condition
572 printPHICopy(CurrBB,TrueBB);
573 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
574 } else if (TrueBB==NULL) {
575 // If "TrueBB" not used the jump is unconditional
576 printPHICopy(CurrBB,FalseBB);
577 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
578 } else {
579 // Copy PHI instructions for each block
580 std::string TmpLabel;
581 // Print PHI instructions for "TrueBB"
582 if (isa<PHINode>(TrueBB->begin())) {
583 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
584 printSimpleInstruction("brtrue",TmpLabel.c_str());
585 } else {
586 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
587 }
588 // Print PHI instructions for "FalseBB"
589 if (isa<PHINode>(FalseBB->begin())) {
590 printPHICopy(CurrBB,FalseBB);
591 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
592 } else {
593 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
594 }
595 if (isa<PHINode>(TrueBB->begin())) {
596 // Handle "TrueBB" PHI Copy
597 Out << TmpLabel << ":\n";
598 printPHICopy(CurrBB,TrueBB);
599 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
600 }
601 }
602}
603
604
605void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
606 if (Inst->isUnconditional()) {
607 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
608 } else {
609 printValueLoad(Inst->getCondition());
610 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
611 Inst->getSuccessor(1));
612 }
613}
614
615
616void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
617 const Value* VFalse) {
618 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
619 printValueLoad(VTrue);
620 printValueLoad(Cond);
621 printSimpleInstruction("brtrue",TmpLabel.c_str());
622 printSimpleInstruction("pop");
623 printValueLoad(VFalse);
624 Out << TmpLabel << ":\n";
625}
626
627
628void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000629 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000630 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000631 if (const PointerType* P = dyn_cast<PointerType>(Ty))
632 Ty = P->getElementType();
633 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000634 printSimpleInstruction(Tmp.c_str());
635}
636
637
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000638void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000639 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000640 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000641 printIndirectSave(Val->getType());
642}
643
644
645void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000646 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000647 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000648 if (*postfix.begin()=='u') *postfix.begin() = 'i';
649 postfix = "stind."+postfix;
650 printSimpleInstruction(postfix.c_str());
651}
652
653
654void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
655 const Type* Ty) {
656 std::string Tmp("");
657 printValueLoad(V);
658 switch (Op) {
659 // Signed
660 case Instruction::SExt:
661 case Instruction::SIToFP:
662 case Instruction::FPToSI:
663 Tmp = "conv."+getTypePostfix(Ty,false,true);
664 printSimpleInstruction(Tmp.c_str());
665 break;
666 // Unsigned
667 case Instruction::FPTrunc:
668 case Instruction::FPExt:
669 case Instruction::UIToFP:
670 case Instruction::Trunc:
671 case Instruction::ZExt:
672 case Instruction::FPToUI:
673 case Instruction::PtrToInt:
674 case Instruction::IntToPtr:
675 Tmp = "conv."+getTypePostfix(Ty,false);
676 printSimpleInstruction(Tmp.c_str());
677 break;
678 // Do nothing
679 case Instruction::BitCast:
680 // FIXME: meaning that ld*/st* instruction do not change data format.
681 break;
682 default:
683 cerr << "Opcode = " << Op << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000684 LLVM_UNREACHABLE("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000685 }
686}
687
688
689void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
690 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000691 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000692 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000693 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000694 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000695 for (; I!=E; ++I){
696 Size = 0;
697 const Value* IndexValue = I.getOperand();
698 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
699 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
700 // Offset is the sum of all previous structure fields.
701 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000702 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000703 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000704 printSimpleInstruction("add");
705 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000706 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000707 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000708 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000709 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000710 }
711 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000712 if (!isZeroValue(IndexValue)) {
713 // Constant optimization.
714 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
715 if (C->getValue().isNegative()) {
716 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
717 printSimpleInstruction("sub");
718 continue;
719 } else
720 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000721 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000722 printPtrLoad(Size);
723 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000724 printSimpleInstruction("mul");
725 }
726 printSimpleInstruction("add");
727 }
728 }
729}
730
731
732std::string MSILWriter::getCallSignature(const FunctionType* Ty,
733 const Instruction* Inst,
734 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000735 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000736 if (Ty->isVarArg()) Tmp += "vararg ";
737 // Name and return type.
738 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
739 // Function argument type list.
740 unsigned NumParams = Ty->getNumParams();
741 for (unsigned I = 0; I!=NumParams; ++I) {
742 if (I!=0) Tmp += ",";
743 Tmp += getTypeName(Ty->getParamType(I));
744 }
745 // CLR needs to know the exact amount of parameters received by vararg
746 // function, because caller cleans the stack.
747 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000748 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000749 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
750 // Print variable argument types.
751 unsigned NumOperands = Inst->getNumOperands()-Org;
752 if (NumParams<NumOperands) {
753 if (NumParams!=0) Tmp += ", ";
754 Tmp += "... , ";
755 for (unsigned J = NumParams; J!=NumOperands; ++J) {
756 if (J!=NumParams) Tmp += ", ";
757 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
758 }
759 }
760 }
761 return Tmp+")";
762}
763
764
765void MSILWriter::printFunctionCall(const Value* FnVal,
766 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000767 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000768 std::string Name = "";
769 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
770 Name = getConvModopt(Call->getCallingConv());
771 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
772 Name = getConvModopt(Invoke->getCallingConv());
773 else {
774 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000775 LLVM_UNREACHABLE("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000776 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000777 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000778 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000779 Name += getValueName(F);
780 printSimpleInstruction("call",
781 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
782 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000783 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000784 const PointerType* PTy = cast<PointerType>(FnVal->getType());
785 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000786 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000787 printValueLoad(FnVal);
788 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
789 }
790}
791
792
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000793void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
794 std::string Name;
795 switch (Inst->getIntrinsicID()) {
796 case Intrinsic::vastart:
797 Name = getValueName(Inst->getOperand(1));
798 Name.insert(Name.length()-1,"$valist");
799 // Obtain the argument handle.
800 printSimpleInstruction("ldloca",Name.c_str());
801 printSimpleInstruction("arglist");
802 printSimpleInstruction("call",
803 "instance void [mscorlib]System.ArgIterator::.ctor"
804 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
805 // Save as pointer type "void*"
806 printValueLoad(Inst->getOperand(1));
807 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000808 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000809 break;
810 case Intrinsic::vaend:
811 // Close argument list handle.
812 printIndirectLoad(Inst->getOperand(1));
813 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
814 break;
815 case Intrinsic::vacopy:
816 // Copy "ArgIterator" valuetype.
817 printIndirectLoad(Inst->getOperand(1));
818 printIndirectLoad(Inst->getOperand(2));
819 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
820 break;
821 default:
822 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000823 LLVM_UNREACHABLE("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000824 }
825}
826
827
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000828void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000829 if (isa<IntrinsicInst>(Inst)) {
830 // Handle intrinsic function.
831 printIntrinsicCall(cast<IntrinsicInst>(Inst));
832 } else {
833 // Load arguments to stack and call function.
834 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
835 printValueLoad(Inst->getOperand(I));
836 printFunctionCall(Inst->getOperand(0),Inst);
837 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000838}
839
840
841void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
842 const Value* Right) {
843 switch (Predicate) {
844 case ICmpInst::ICMP_EQ:
845 printBinaryInstruction("ceq",Left,Right);
846 break;
847 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000848 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000849 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000850 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000851 printSimpleInstruction("not");
852 break;
853 case ICmpInst::ICMP_ULE:
854 case ICmpInst::ICMP_SLE:
855 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
856 printBinaryInstruction("ceq",Left,Right);
857 if (Predicate==ICmpInst::ICMP_ULE)
858 printBinaryInstruction("clt.un",Left,Right);
859 else
860 printBinaryInstruction("clt",Left,Right);
861 printSimpleInstruction("or");
862 break;
863 case ICmpInst::ICMP_UGE:
864 case ICmpInst::ICMP_SGE:
865 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
866 printBinaryInstruction("ceq",Left,Right);
867 if (Predicate==ICmpInst::ICMP_UGE)
868 printBinaryInstruction("cgt.un",Left,Right);
869 else
870 printBinaryInstruction("cgt",Left,Right);
871 printSimpleInstruction("or");
872 break;
873 case ICmpInst::ICMP_ULT:
874 printBinaryInstruction("clt.un",Left,Right);
875 break;
876 case ICmpInst::ICMP_SLT:
877 printBinaryInstruction("clt",Left,Right);
878 break;
879 case ICmpInst::ICMP_UGT:
880 printBinaryInstruction("cgt.un",Left,Right);
881 case ICmpInst::ICMP_SGT:
882 printBinaryInstruction("cgt",Left,Right);
883 break;
884 default:
885 cerr << "Predicate = " << Predicate << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +0000886 LLVM_UNREACHABLE("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000887 }
888}
889
890
891void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
892 const Value* Right) {
893 // FIXME: Correct comparison
894 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
895 switch (Predicate) {
896 case FCmpInst::FCMP_UGT:
897 // X > Y || llvm_fcmp_uno(X, Y)
898 printBinaryInstruction("cgt",Left,Right);
899 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
900 printSimpleInstruction("or");
901 break;
902 case FCmpInst::FCMP_OGT:
903 // X > Y
904 printBinaryInstruction("cgt",Left,Right);
905 break;
906 case FCmpInst::FCMP_UGE:
907 // X >= Y || llvm_fcmp_uno(X, Y)
908 printBinaryInstruction("ceq",Left,Right);
909 printBinaryInstruction("cgt",Left,Right);
910 printSimpleInstruction("or");
911 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
912 printSimpleInstruction("or");
913 break;
914 case FCmpInst::FCMP_OGE:
915 // X >= Y
916 printBinaryInstruction("ceq",Left,Right);
917 printBinaryInstruction("cgt",Left,Right);
918 printSimpleInstruction("or");
919 break;
920 case FCmpInst::FCMP_ULT:
921 // X < Y || llvm_fcmp_uno(X, Y)
922 printBinaryInstruction("clt",Left,Right);
923 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
924 printSimpleInstruction("or");
925 break;
926 case FCmpInst::FCMP_OLT:
927 // X < Y
928 printBinaryInstruction("clt",Left,Right);
929 break;
930 case FCmpInst::FCMP_ULE:
931 // X <= Y || llvm_fcmp_uno(X, Y)
932 printBinaryInstruction("ceq",Left,Right);
933 printBinaryInstruction("clt",Left,Right);
934 printSimpleInstruction("or");
935 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
936 printSimpleInstruction("or");
937 break;
938 case FCmpInst::FCMP_OLE:
939 // X <= Y
940 printBinaryInstruction("ceq",Left,Right);
941 printBinaryInstruction("clt",Left,Right);
942 printSimpleInstruction("or");
943 break;
944 case FCmpInst::FCMP_UEQ:
945 // X == Y || llvm_fcmp_uno(X, Y)
946 printBinaryInstruction("ceq",Left,Right);
947 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
948 printSimpleInstruction("or");
949 break;
950 case FCmpInst::FCMP_OEQ:
951 // X == Y
952 printBinaryInstruction("ceq",Left,Right);
953 break;
954 case FCmpInst::FCMP_UNE:
955 // X != Y
956 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000957 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000958 printSimpleInstruction("not");
959 break;
960 case FCmpInst::FCMP_ONE:
961 // X != Y && llvm_fcmp_ord(X, Y)
962 printBinaryInstruction("ceq",Left,Right);
963 printSimpleInstruction("not");
964 break;
965 case FCmpInst::FCMP_ORD:
966 // return X == X && Y == Y
967 printBinaryInstruction("ceq",Left,Left);
968 printBinaryInstruction("ceq",Right,Right);
969 printSimpleInstruction("or");
970 break;
971 case FCmpInst::FCMP_UNO:
972 // X != X || Y != Y
973 printBinaryInstruction("ceq",Left,Left);
974 printSimpleInstruction("not");
975 printBinaryInstruction("ceq",Right,Right);
976 printSimpleInstruction("not");
977 printSimpleInstruction("or");
978 break;
979 default:
Torok Edwinc25e7582009-07-11 20:10:48 +0000980 LLVM_UNREACHABLE("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000981 }
982}
983
984
985void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
986 std::string Label = "leave$normal_"+utostr(getUniqID());
987 Out << ".try {\n";
988 // Load arguments
989 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
990 printValueLoad(Inst->getOperand(I));
991 // Print call instruction
992 printFunctionCall(Inst->getOperand(0),Inst);
993 // Save function result and leave "try" block
994 printValueSave(Inst);
995 printSimpleInstruction("leave",Label.c_str());
996 Out << "}\n";
997 Out << "catch [mscorlib]System.Exception {\n";
998 // Redirect to unwind block
999 printSimpleInstruction("pop");
1000 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1001 Out << "}\n" << Label << ":\n";
1002 // Redirect to continue block
1003 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1004}
1005
1006
1007void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1008 // FIXME: Emulate with IL "switch" instruction
1009 // Emulate = if () else if () else if () else ...
1010 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1011 printValueLoad(Inst->getCondition());
1012 printValueLoad(Inst->getCaseValue(I));
1013 printSimpleInstruction("ceq");
1014 // Condition jump to successor block
1015 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1016 }
1017 // Jump to default block
1018 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1019}
1020
1021
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001022void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1023 printIndirectLoad(Inst->getOperand(0));
1024 printSimpleInstruction("call",
1025 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1026 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001027 std::string Name =
1028 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001029 printSimpleInstruction(Name.c_str());
1030}
1031
1032
1033void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001034 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001035 // Constant optimization.
1036 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1037 printPtrLoad(CInt->getZExtValue()*Size);
1038 } else {
1039 printPtrLoad(Size);
1040 printValueLoad(Inst->getOperand(0));
1041 printSimpleInstruction("mul");
1042 }
1043 printSimpleInstruction("localloc");
1044}
1045
1046
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001047void MSILWriter::printInstruction(const Instruction* Inst) {
1048 const Value *Left = 0, *Right = 0;
1049 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1050 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1051 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001052 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001053 switch (Inst->getOpcode()) {
1054 // Terminator
1055 case Instruction::Ret:
1056 if (Inst->getNumOperands()) {
1057 printValueLoad(Left);
1058 printSimpleInstruction("ret");
1059 } else
1060 printSimpleInstruction("ret");
1061 break;
1062 case Instruction::Br:
1063 printBranchInstruction(cast<BranchInst>(Inst));
1064 break;
1065 // Binary
1066 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001067 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001068 printBinaryInstruction("add",Left,Right);
1069 break;
1070 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001071 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001072 printBinaryInstruction("sub",Left,Right);
1073 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001074 case Instruction::Mul:
1075 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001076 printBinaryInstruction("mul",Left,Right);
1077 break;
1078 case Instruction::UDiv:
1079 printBinaryInstruction("div.un",Left,Right);
1080 break;
1081 case Instruction::SDiv:
1082 case Instruction::FDiv:
1083 printBinaryInstruction("div",Left,Right);
1084 break;
1085 case Instruction::URem:
1086 printBinaryInstruction("rem.un",Left,Right);
1087 break;
1088 case Instruction::SRem:
1089 case Instruction::FRem:
1090 printBinaryInstruction("rem",Left,Right);
1091 break;
1092 // Binary Condition
1093 case Instruction::ICmp:
1094 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1095 break;
1096 case Instruction::FCmp:
1097 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1098 break;
1099 // Bitwise Binary
1100 case Instruction::And:
1101 printBinaryInstruction("and",Left,Right);
1102 break;
1103 case Instruction::Or:
1104 printBinaryInstruction("or",Left,Right);
1105 break;
1106 case Instruction::Xor:
1107 printBinaryInstruction("xor",Left,Right);
1108 break;
1109 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001110 printValueLoad(Left);
1111 printValueLoad(Right);
1112 printSimpleInstruction("conv.i4");
1113 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001114 break;
1115 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001116 printValueLoad(Left);
1117 printValueLoad(Right);
1118 printSimpleInstruction("conv.i4");
1119 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001120 break;
1121 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001122 printValueLoad(Left);
1123 printValueLoad(Right);
1124 printSimpleInstruction("conv.i4");
1125 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001126 break;
1127 case Instruction::Select:
1128 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1129 break;
1130 case Instruction::Load:
1131 printIndirectLoad(Inst->getOperand(0));
1132 break;
1133 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001134 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001135 break;
1136 case Instruction::Trunc:
1137 case Instruction::ZExt:
1138 case Instruction::SExt:
1139 case Instruction::FPTrunc:
1140 case Instruction::FPExt:
1141 case Instruction::UIToFP:
1142 case Instruction::SIToFP:
1143 case Instruction::FPToUI:
1144 case Instruction::FPToSI:
1145 case Instruction::PtrToInt:
1146 case Instruction::IntToPtr:
1147 case Instruction::BitCast:
1148 printCastInstruction(Inst->getOpcode(),Left,
1149 cast<CastInst>(Inst)->getDestTy());
1150 break;
1151 case Instruction::GetElementPtr:
1152 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1153 gep_type_end(Inst));
1154 break;
1155 case Instruction::Call:
1156 printCallInstruction(cast<CallInst>(Inst));
1157 break;
1158 case Instruction::Invoke:
1159 printInvokeInstruction(cast<InvokeInst>(Inst));
1160 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001161 case Instruction::Unwind:
1162 printSimpleInstruction("newobj",
1163 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001164 printSimpleInstruction("throw");
1165 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001166 case Instruction::Switch:
1167 printSwitchInstruction(cast<SwitchInst>(Inst));
1168 break;
1169 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001170 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001171 break;
1172 case Instruction::Malloc:
Torok Edwinc25e7582009-07-11 20:10:48 +00001173 LLVM_UNREACHABLE("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001174 break;
1175 case Instruction::Free:
Torok Edwinc25e7582009-07-11 20:10:48 +00001176 LLVM_UNREACHABLE("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001177 break;
1178 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001179 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1180 printSimpleInstruction("newobj",
1181 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001182 printSimpleInstruction("throw");
1183 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001184 case Instruction::VAArg:
1185 printVAArgInstruction(cast<VAArgInst>(Inst));
1186 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001187 default:
1188 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +00001189 LLVM_UNREACHABLE("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001190 }
1191}
1192
1193
1194void MSILWriter::printLoop(const Loop* L) {
1195 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1196 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1197 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1198 BasicBlock* BB = blocks[I];
1199 Loop* BBLoop = LInfo->getLoopFor(BB);
1200 if (BBLoop == L)
1201 printBasicBlock(BB);
1202 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1203 printLoop(BBLoop);
1204 }
1205 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1206}
1207
1208
1209void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1210 Out << getLabelName(BB) << ":\n";
1211 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1212 const Instruction* Inst = I;
1213 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001214 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001215 // Do not handle PHI instruction in current block
1216 if (Inst->getOpcode()==Instruction::PHI) continue;
1217 // Print instruction
1218 printInstruction(Inst);
1219 // Save result
1220 if (Inst->getType()!=Type::VoidTy) {
1221 // Do not save value after invoke, it done in "try" block
1222 if (Inst->getOpcode()==Instruction::Invoke) continue;
1223 printValueSave(Inst);
1224 }
1225 }
1226}
1227
1228
1229void MSILWriter::printLocalVariables(const Function& F) {
1230 std::string Name;
1231 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001232 std::set<const Value*> Printed;
1233 const Value* VaList = NULL;
1234 unsigned StackDepth = 8;
1235 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001236 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001237 if (I->getOpcode()==Instruction::Call ||
1238 I->getOpcode()==Instruction::Invoke) {
1239 // Test stack depth.
1240 if (StackDepth<I->getNumOperands())
1241 StackDepth = I->getNumOperands();
1242 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001243 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1244 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001245 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001246 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001247 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001248 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001249 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001250 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001251 Ty = I->getType();
1252 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001253 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1254 }
1255 // Test on 'va_list' variable
1256 bool isVaList = false;
1257 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1258 // "va_list" as "va_arg" instruction operand.
1259 isVaList = true;
1260 VaList = VaInst->getOperand(0);
1261 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1262 // "va_list" as intrinsic function operand.
1263 switch (Inst->getIntrinsicID()) {
1264 case Intrinsic::vastart:
1265 case Intrinsic::vaend:
1266 case Intrinsic::vacopy:
1267 isVaList = true;
1268 VaList = Inst->getOperand(1);
1269 break;
1270 default:
1271 isVaList = false;
1272 }
1273 }
1274 // Print "va_list" variable.
1275 if (isVaList && Printed.insert(VaList).second) {
1276 Name = getValueName(VaList);
1277 Name.insert(Name.length()-1,"$valist");
1278 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1279 << Name << ")\n";
1280 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001281 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001282 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001283}
1284
1285
1286void MSILWriter::printFunctionBody(const Function& F) {
1287 // Print body
1288 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1289 if (Loop *L = LInfo->getLoopFor(I)) {
1290 if (L->getHeader()==I && L->getParentLoop()==0)
1291 printLoop(L);
1292 } else {
1293 printBasicBlock(I);
1294 }
1295 }
1296}
1297
1298
1299void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1300 const Value *left = 0, *right = 0;
1301 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1302 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1303 // Print instruction
1304 switch (CE->getOpcode()) {
1305 case Instruction::Trunc:
1306 case Instruction::ZExt:
1307 case Instruction::SExt:
1308 case Instruction::FPTrunc:
1309 case Instruction::FPExt:
1310 case Instruction::UIToFP:
1311 case Instruction::SIToFP:
1312 case Instruction::FPToUI:
1313 case Instruction::FPToSI:
1314 case Instruction::PtrToInt:
1315 case Instruction::IntToPtr:
1316 case Instruction::BitCast:
1317 printCastInstruction(CE->getOpcode(),left,CE->getType());
1318 break;
1319 case Instruction::GetElementPtr:
1320 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1321 break;
1322 case Instruction::ICmp:
1323 printICmpInstruction(CE->getPredicate(),left,right);
1324 break;
1325 case Instruction::FCmp:
1326 printFCmpInstruction(CE->getPredicate(),left,right);
1327 break;
1328 case Instruction::Select:
1329 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1330 break;
1331 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001332 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001333 printBinaryInstruction("add",left,right);
1334 break;
1335 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001336 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001337 printBinaryInstruction("sub",left,right);
1338 break;
1339 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001340 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001341 printBinaryInstruction("mul",left,right);
1342 break;
1343 case Instruction::UDiv:
1344 printBinaryInstruction("div.un",left,right);
1345 break;
1346 case Instruction::SDiv:
1347 case Instruction::FDiv:
1348 printBinaryInstruction("div",left,right);
1349 break;
1350 case Instruction::URem:
1351 printBinaryInstruction("rem.un",left,right);
1352 break;
1353 case Instruction::SRem:
1354 case Instruction::FRem:
1355 printBinaryInstruction("rem",left,right);
1356 break;
1357 case Instruction::And:
1358 printBinaryInstruction("and",left,right);
1359 break;
1360 case Instruction::Or:
1361 printBinaryInstruction("or",left,right);
1362 break;
1363 case Instruction::Xor:
1364 printBinaryInstruction("xor",left,right);
1365 break;
1366 case Instruction::Shl:
1367 printBinaryInstruction("shl",left,right);
1368 break;
1369 case Instruction::LShr:
1370 printBinaryInstruction("shr.un",left,right);
1371 break;
1372 case Instruction::AShr:
1373 printBinaryInstruction("shr",left,right);
1374 break;
1375 default:
1376 cerr << "Expression = " << *CE << "\n";
Torok Edwinc25e7582009-07-11 20:10:48 +00001377 LLVM_UNREACHABLE("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001378 }
1379}
1380
1381
1382void MSILWriter::printStaticInitializerList() {
1383 // List of global variables with uninitialized fields.
1384 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1385 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1386 ++VarI) {
1387 const std::vector<StaticInitializer>& InitList = VarI->second;
1388 if (InitList.empty()) continue;
1389 // For each uninitialized field.
1390 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1391 E = InitList.end(); I!=E; ++I) {
1392 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001393 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1394 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001395 // Load variable address
1396 printValueLoad(VarI->first);
1397 // Add offset
1398 if (I->offset!=0) {
1399 printPtrLoad(I->offset);
1400 printSimpleInstruction("add");
1401 }
1402 // Load value
1403 printConstantExpr(CE);
1404 // Save result at offset
1405 std::string postfix = getTypePostfix(CE->getType(),true);
1406 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1407 postfix = "stind."+postfix;
1408 printSimpleInstruction(postfix.c_str());
1409 } else {
1410 cerr << "Constant = " << *I->constant << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +00001411 LLVM_UNREACHABLE("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001412 }
1413 }
1414 }
1415}
1416
1417
1418void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001419 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001420 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001421 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001422 if (F.isVarArg()) Out << "vararg ";
1423 Out << getTypeName(F.getReturnType(),isSigned) <<
1424 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1425 // Arguments
1426 Out << "\t(";
1427 unsigned ArgIdx = 1;
1428 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1429 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001430 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001431 if (I!=F.arg_begin()) Out << ", ";
1432 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1433 }
1434 Out << ") cil managed\n";
1435 // Body
1436 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001437 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001438 printFunctionBody(F);
1439 Out << "}\n";
1440}
1441
1442
1443void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1444 std::string Name;
1445 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001446 for (std::set<const Type*>::const_iterator
1447 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1448 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001449 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1450 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001451 // Type with no need to declare.
1452 else continue;
1453 // Print not duplicated type
1454 if (Printed.insert(Ty).second) {
1455 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001456 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001457 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001458 }
1459 }
1460}
1461
1462
1463unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1464 unsigned int N = Ty->getPrimitiveSizeInBits();
1465 assert(N!=0 && "Invalid type in getBitWidth()");
1466 switch (N) {
1467 case 1:
1468 case 8:
1469 case 16:
1470 case 32:
1471 case 64:
1472 return N;
1473 default:
1474 cerr << "Bits = " << N << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +00001475 LLVM_UNREACHABLE("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001476 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001477 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001478}
1479
1480
1481void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1482 uint64_t TySize = 0;
1483 const Type* Ty = C->getType();
1484 // Print zero initialized constant.
1485 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001486 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001487 Offset += TySize;
1488 Out << "int8 (0) [" << TySize << "]";
1489 return;
1490 }
1491 // Print constant initializer
1492 switch (Ty->getTypeID()) {
1493 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001494 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001495 const ConstantInt* Int = cast<ConstantInt>(C);
1496 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1497 break;
1498 }
1499 case Type::FloatTyID:
1500 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001501 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001502 const ConstantFP* FP = cast<ConstantFP>(C);
1503 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001504 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001505 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001506 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001507 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001508 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001509 break;
1510 }
1511 case Type::ArrayTyID:
1512 case Type::VectorTyID:
1513 case Type::StructTyID:
1514 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1515 if (I!=0) Out << ",\n";
1516 printStaticConstant(C->getOperand(I),Offset);
1517 }
1518 break;
1519 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001520 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001521 // Initialize with global variable address
1522 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1523 std::string name = getValueName(G);
1524 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1525 } else {
1526 // Dynamic initialization
1527 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1528 InitListPtr->push_back(StaticInitializer(C,Offset));
1529 // Null pointer initialization
1530 if (TySize==4) Out << "int32 (0)";
1531 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc25e7582009-07-11 20:10:48 +00001532 else LLVM_UNREACHABLE("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001533 }
1534 break;
1535 default:
1536 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc25e7582009-07-11 20:10:48 +00001537 LLVM_UNREACHABLE("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001538 }
1539 // Increase offset.
1540 Offset += TySize;
1541}
1542
1543
1544void MSILWriter::printStaticInitializer(const Constant* C,
1545 const std::string& Name) {
1546 switch (C->getType()->getTypeID()) {
1547 case Type::IntegerTyID:
1548 case Type::FloatTyID:
1549 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001550 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001551 break;
1552 case Type::ArrayTyID:
1553 case Type::VectorTyID:
1554 case Type::StructTyID:
1555 case Type::PointerTyID:
1556 Out << getTypeName(C->getType());
1557 break;
1558 default:
1559 cerr << "Type = " << *C << "\n";
Torok Edwinc25e7582009-07-11 20:10:48 +00001560 LLVM_UNREACHABLE("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001561 }
1562 // Print initializer
1563 std::string label = Name;
1564 label.insert(label.length()-1,"$data");
1565 Out << Name << " at " << label << '\n';
1566 Out << ".data " << label << " = {\n";
1567 uint64_t offset = 0;
1568 printStaticConstant(C,offset);
1569 Out << "\n}\n\n";
1570}
1571
1572
1573void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1574 const Constant* C = G->getInitializer();
1575 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1576 InitListPtr = 0;
1577 else
1578 InitListPtr = &StaticInitList[G];
1579 printStaticInitializer(C,getValueName(G));
1580}
1581
1582
1583void MSILWriter::printGlobalVariables() {
1584 if (ModulePtr->global_empty()) return;
1585 Module::global_iterator I,E;
1586 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1587 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001588 Out << ".field static " << (I->isDeclaration() ? "public " :
1589 "private ");
1590 if (I->isDeclaration()) {
1591 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1592 } else
1593 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001594 }
1595}
1596
1597
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001598const char* MSILWriter::getLibraryName(const Function* F) {
1599 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1600}
1601
1602
1603const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
1604 return getLibraryForSymbol(Mang->getValueName(GV).c_str(), false, 0);
1605}
1606
1607
1608const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1609 unsigned CallingConv) {
1610 // TODO: Read *.def file with function and libraries definitions.
1611 return "MSVCRT.DLL";
1612}
1613
1614
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001615void MSILWriter::printExternals() {
1616 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001617 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001618 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1619 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001620 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001621 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001622 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001623 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001624 std::string Sig =
1625 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1626 Out << ".method static hidebysig pinvokeimpl(\""
1627 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001628 }
1629 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001630 // External variables and static initialization.
1631 Out <<
1632 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1633 " native int LoadLibrary(string) preservesig {}\n"
1634 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1635 " native int GetProcAddress(native int, string) preservesig {}\n";
1636 Out <<
1637 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1638 " managed cil\n{\n"
1639 "\tldarg\tlib\n"
1640 "\tcall\tnative int LoadLibrary(string)\n"
1641 "\tldarg\tsym\n"
1642 "\tcall\tnative int GetProcAddress(native int,string)\n"
1643 "\tdup\n"
1644 "\tbrtrue\tL_01\n"
1645 "\tldstr\t\"Can no import variable\"\n"
1646 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1647 "\tthrow\n"
1648 "L_01:\n"
1649 "\tret\n"
1650 "}\n\n"
1651 ".method static private void $MSIL_Init() managed cil\n{\n";
1652 printStaticInitializerList();
1653 // Foreach global variable.
1654 for (Module::global_iterator I = ModulePtr->global_begin(),
1655 E = ModulePtr->global_end(); I!=E; ++I) {
1656 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1657 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1658 std::string Label = "not_null$_"+utostr(getUniqID());
1659 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1660 printSimpleInstruction("ldsflda",Tmp.c_str());
1661 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
1662 Out << "\tldstr\t\"" << Mang->getValueName(&*I) << "\"\n";
1663 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1664 printIndirectSave(I->getType());
1665 }
1666 printSimpleInstruction("ret");
1667 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001668}
1669
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001670
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001671//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001672// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001673//===----------------------------------------------------------------------===//
1674
Owen Andersoncb371882008-08-21 00:14:44 +00001675bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM, raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001676 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001677 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001678{
1679 if (FileType != TargetMachine::AssemblyFile) return true;
1680 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001681 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001682 PM.add(createLowerAllocationsPass(true));
1683 // FIXME: Handle switch trougth native IL instruction "switch"
1684 PM.add(createLowerSwitchPass());
1685 PM.add(createCFGSimplificationPass());
1686 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1687 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001688 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001689 return false;
1690}