blob: bedf40385d5652d83d63ad950e1b64292fbff37f [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
Daniel Dunbar51b198a2009-07-15 20:24:03 +000034 MSILTarget(const Target &T, const Module &M, const std::string &FS)
35 : TargetMachine(T), DataLayout(&M) {}
Anton Korobeynikov099883f2007-03-21 21:38:25 +000036
37 virtual bool WantsWholeFile() const { return true; }
David Greene71847812009-07-14 20:18:05 +000038 virtual bool addPassesToEmitWholeFile(PassManager &PM,
39 formatted_raw_ostream &Out,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000040 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +000041 CodeGenOpt::Level OptLevel);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000042
43 // This class always works, but shouldn't be the default in most cases.
44 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
45
46 virtual const TargetData *getTargetData() const { return &DataLayout; }
47 };
48}
49
Oscar Fuentes92adc192008-11-15 21:36:30 +000050/// MSILTargetMachineModule - Note that this is used on hosts that
51/// cannot link in a library unless there are references into the
52/// library. In particular, it seems that it is not possible to get
53/// things to work on Win32 without this. Though it is unused, do not
54/// remove it.
55extern "C" int MSILTargetMachineModule;
56int MSILTargetMachineModule = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000057
Daniel Dunbar51b198a2009-07-15 20:24:03 +000058extern Target TheMSILTarget;
59static RegisterTarget<MSILTarget> X(TheMSILTarget, "msil", "MSIL backend");
Anton Korobeynikov099883f2007-03-21 21:38:25 +000060
Bob Wilsona96751f2009-06-23 23:59:40 +000061// Force static initialization.
62extern "C" void LLVMInitializeMSILTarget() { }
Douglas Gregor1555a232009-06-16 20:12:29 +000063
Anton Korobeynikov099883f2007-03-21 21:38:25 +000064bool MSILModule::runOnModule(Module &M) {
65 ModulePtr = &M;
66 TD = &getAnalysis<TargetData>();
67 bool Changed = false;
68 // Find named types.
69 TypeSymbolTable& Table = M.getTypeSymbolTable();
70 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
71 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
72 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
73 Table.remove(I++);
74 else {
75 std::set<const Type *>::iterator T = Types.find(I->second);
76 if (T==Types.end())
77 Table.remove(I++);
78 else {
79 Types.erase(T);
80 ++I;
81 }
82 }
83 }
84 // Find unnamed types.
85 unsigned RenameCounter = 0;
86 for (std::set<const Type *>::const_iterator I = Types.begin(),
87 E = Types.end(); I!=E; ++I)
88 if (const StructType *STy = dyn_cast<StructType>(*I)) {
89 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
90 ++RenameCounter;
91 Changed = true;
92 }
93 // Pointer for FunctionPass.
94 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
95 return Changed;
96}
97
Devang Patel19974732007-05-03 01:11:54 +000098char MSILModule::ID = 0;
99char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000100
101bool MSILWriter::runOnFunction(Function &F) {
102 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +0000103
104 // Do not codegen any 'available_externally' functions at all, they have
105 // definitions outside the translation unit.
106 if (F.hasAvailableExternallyLinkage())
107 return false;
108
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000109 LInfo = &getAnalysis<LoopInfo>();
110 printFunction(F);
111 return false;
112}
113
114
115bool MSILWriter::doInitialization(Module &M) {
116 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000117 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000118 Out << ".assembly extern mscorlib {}\n";
119 Out << ".assembly MSIL {}\n\n";
120 Out << "// External\n";
121 printExternals();
122 Out << "// Declarations\n";
123 printDeclarations(M.getTypeSymbolTable());
124 Out << "// Definitions\n";
125 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000126 Out << "// Startup code\n";
127 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000128 return false;
129}
130
131
132bool MSILWriter::doFinalization(Module &M) {
133 delete Mang;
134 return false;
135}
136
137
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000138void MSILWriter::printModuleStartup() {
139 Out <<
140 ".method static public int32 $MSIL_Startup() {\n"
141 "\t.entrypoint\n"
142 "\t.locals (native int i)\n"
143 "\t.locals (native int argc)\n"
144 "\t.locals (native int ptr)\n"
145 "\t.locals (void* argv)\n"
146 "\t.locals (string[] args)\n"
147 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
148 "\tdup\n"
149 "\tstloc\targs\n"
150 "\tldlen\n"
151 "\tconv.i4\n"
152 "\tdup\n"
153 "\tstloc\targc\n";
154 printPtrLoad(TD->getPointerSize());
155 Out <<
156 "\tmul\n"
157 "\tlocalloc\n"
158 "\tstloc\targv\n"
159 "\tldc.i4.0\n"
160 "\tstloc\ti\n"
161 "L_01:\n"
162 "\tldloc\ti\n"
163 "\tldloc\targc\n"
164 "\tceq\n"
165 "\tbrtrue\tL_02\n"
166 "\tldloc\targs\n"
167 "\tldloc\ti\n"
168 "\tldelem.ref\n"
169 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
170 "StringToHGlobalAnsi(string)\n"
171 "\tstloc\tptr\n"
172 "\tldloc\targv\n"
173 "\tldloc\ti\n";
174 printPtrLoad(TD->getPointerSize());
175 Out <<
176 "\tmul\n"
177 "\tadd\n"
178 "\tldloc\tptr\n"
179 "\tstind.i\n"
180 "\tldloc\ti\n"
181 "\tldc.i4.1\n"
182 "\tadd\n"
183 "\tstloc\ti\n"
184 "\tbr\tL_01\n"
185 "L_02:\n"
186 "\tcall void $MSIL_Init()\n";
187
188 // Call user 'main' function.
189 const Function* F = ModulePtr->getFunction("main");
190 if (!F || F->isDeclaration()) {
191 Out << "\tldc.i4.0\n\tret\n}\n";
192 return;
193 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000194 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000195 std::string Args("");
196 Function::const_arg_iterator Arg1,Arg2;
197
198 switch (F->arg_size()) {
199 case 0:
200 BadSig = false;
201 break;
202 case 1:
203 Arg1 = F->arg_begin();
204 if (Arg1->getType()->isInteger()) {
205 Out << "\tldloc\targc\n";
206 Args = getTypeName(Arg1->getType());
207 BadSig = false;
208 }
209 break;
210 case 2:
211 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
212 if (Arg1->getType()->isInteger() &&
213 Arg2->getType()->getTypeID() == Type::PointerTyID) {
214 Out << "\tldloc\targc\n\tldloc\targv\n";
215 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
216 BadSig = false;
217 }
218 break;
219 default:
220 BadSig = true;
221 }
222
223 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000224 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000225 Out << "\tldc.i4.0\n";
226 } else {
227 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
228 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
229 if (RetVoid)
230 Out << "\tldc.i4.0\n";
231 else
232 Out << "\tconv.i4\n";
233 }
234 Out << "\tret\n}\n";
235}
236
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000237bool MSILWriter::isZeroValue(const Value* V) {
238 if (const Constant *C = dyn_cast<Constant>(V))
239 return C->isNullValue();
240 return false;
241}
242
243
244std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000245 std::string Name;
246 if (const GlobalValue *GV = cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000247 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000248 else {
249 unsigned &No = AnonValueNumbers[V];
250 if (No == 0) No = ++NextAnonValueNumber;
251 Name = "tmp" + utostr(No);
252 }
253
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000254 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000255 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000256}
257
258
259std::string MSILWriter::getLabelName(const std::string& Name) {
260 if (Name.find('.')!=std::string::npos) {
261 std::string Tmp(Name);
262 // Replace unaccepable characters in the label name.
263 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
264 if (*I=='.') *I = '@';
265 return Tmp;
266 }
267 return Name;
268}
269
270
271std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000272 std::string Name;
273 if (const GlobalValue *GV = cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000274 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000275 else {
276 unsigned &No = AnonValueNumbers[V];
277 if (No == 0) No = ++NextAnonValueNumber;
278 Name = "tmp" + utostr(No);
279 }
280
281 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000282}
283
284
285std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
286 switch (CallingConvID) {
287 case CallingConv::C:
288 case CallingConv::Cold:
289 case CallingConv::Fast:
290 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
291 case CallingConv::X86_FastCall:
292 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
293 case CallingConv::X86_StdCall:
294 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
295 default:
296 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000297 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000298 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000299 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000300}
301
302
303std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
304 std::string Tmp = "";
305 const Type* ElemTy = Ty;
306 assert(Ty->getTypeID()==TyID && "Invalid type passed");
307 // Walk trought array element types.
308 for (;;) {
309 // Multidimensional array.
310 if (ElemTy->getTypeID()==TyID) {
311 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
312 Tmp += utostr(ATy->getNumElements());
313 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
314 Tmp += utostr(VTy->getNumElements());
315 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
316 }
317 // Base element type found.
318 if (ElemTy->getTypeID()!=TyID) break;
319 Tmp += ",";
320 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000321 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000322}
323
324
325std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
326 unsigned NumBits = 0;
327 switch (Ty->getTypeID()) {
328 case Type::VoidTyID:
329 return "void ";
330 case Type::IntegerTyID:
331 NumBits = getBitWidth(Ty);
332 if(NumBits==1)
333 return "bool ";
334 if (!isSigned)
335 return "unsigned int"+utostr(NumBits)+" ";
336 return "int"+utostr(NumBits)+" ";
337 case Type::FloatTyID:
338 return "float32 ";
339 case Type::DoubleTyID:
340 return "float64 ";
341 default:
342 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000343 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000344 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000345 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000346}
347
348
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000349std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
350 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000351 if (Ty->isPrimitiveType() || Ty->isInteger())
352 return getPrimitiveTypeName(Ty,isSigned);
353 // FIXME: "OpaqueType" support
354 switch (Ty->getTypeID()) {
355 case Type::PointerTyID:
356 return "void* ";
357 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000358 if (isNested)
359 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000360 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
361 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000362 if (isNested)
363 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000364 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
365 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000366 if (isNested)
367 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000368 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
369 default:
370 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000371 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000372 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000373 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000374}
375
376
377MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
378 // Function argument
379 if (isa<Argument>(V))
380 return ArgumentVT;
381 // Function
382 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000383 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000384 // Variable
385 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000386 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000387 // Constant
388 else if (isa<Constant>(V))
389 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
390 // Local variable
391 return LocalVT;
392}
393
394
395std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
396 bool isSigned) {
397 unsigned NumBits = 0;
398 switch (Ty->getTypeID()) {
399 // Integer constant, expanding for stack operations.
400 case Type::IntegerTyID:
401 NumBits = getBitWidth(Ty);
402 // Expand integer value to "int32" or "int64".
403 if (Expand) return (NumBits<=32 ? "i4" : "i8");
404 if (NumBits==1) return "i1";
405 return (isSigned ? "i" : "u")+utostr(NumBits/8);
406 // Float constant.
407 case Type::FloatTyID:
408 return "r4";
409 case Type::DoubleTyID:
410 return "r8";
411 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000412 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000413 default:
414 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000415 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000416 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000417 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000418}
419
420
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000421void MSILWriter::printConvToPtr() {
422 switch (ModulePtr->getPointerSize()) {
423 case Module::Pointer32:
424 printSimpleInstruction("conv.u4");
425 break;
426 case Module::Pointer64:
427 printSimpleInstruction("conv.u8");
428 break;
429 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000430 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000431 }
432}
433
434
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000435void MSILWriter::printPtrLoad(uint64_t N) {
436 switch (ModulePtr->getPointerSize()) {
437 case Module::Pointer32:
438 printSimpleInstruction("ldc.i4",utostr(N).c_str());
439 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000440 if (!isUInt32(N)) {
441 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000442 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000443 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000444 break;
445 case Module::Pointer64:
446 printSimpleInstruction("ldc.i8",utostr(N).c_str());
447 break;
448 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000449 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000450 }
451}
452
453
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000454void MSILWriter::printValuePtrLoad(const Value* V) {
455 printValueLoad(V);
456 printConvToPtr();
457}
458
459
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000460void MSILWriter::printConstLoad(const Constant* C) {
461 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
462 // Integer constant
463 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
464 if (CInt->isMinValue(true))
465 Out << CInt->getSExtValue();
466 else
467 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000468 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000469 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000470 uint64_t X;
471 unsigned Size;
472 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000473 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000474 Size = 4;
475 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000476 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000477 Size = 8;
478 }
479 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
480 } else if (isa<UndefValue>(C)) {
481 // Undefined constant value = NULL.
482 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000483 } else {
484 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000485 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000486 }
487 Out << '\n';
488}
489
490
491void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000492 MSILWriter::ValueType Location = getValueLocation(V);
493 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000494 // Global variable or function address.
495 case GlobalVT:
496 case InternalVT:
497 if (const Function* F = dyn_cast<Function>(V)) {
498 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
499 printSimpleInstruction("ldftn",
500 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
501 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000502 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000503 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000504 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
505 Tmp = "void* "+getValueName(V);
506 printSimpleInstruction("ldsfld",Tmp.c_str());
507 } else {
508 Tmp = getTypeName(ElemTy)+getValueName(V);
509 printSimpleInstruction("ldsflda",Tmp.c_str());
510 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000511 }
512 break;
513 // Function argument.
514 case ArgumentVT:
515 printSimpleInstruction("ldarg",getValueName(V).c_str());
516 break;
517 // Local function variable.
518 case LocalVT:
519 printSimpleInstruction("ldloc",getValueName(V).c_str());
520 break;
521 // Constant value.
522 case ConstVT:
523 if (isa<ConstantPointerNull>(V))
524 printPtrLoad(0);
525 else
526 printConstLoad(cast<Constant>(V));
527 break;
528 // Constant expression.
529 case ConstExprVT:
530 printConstantExpr(cast<ConstantExpr>(V));
531 break;
532 default:
533 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000534 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000535 }
536}
537
538
539void MSILWriter::printValueSave(const Value* V) {
540 switch (getValueLocation(V)) {
541 case ArgumentVT:
542 printSimpleInstruction("starg",getValueName(V).c_str());
543 break;
544 case LocalVT:
545 printSimpleInstruction("stloc",getValueName(V).c_str());
546 break;
547 default:
548 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000549 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000550 }
551}
552
553
554void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
555 const Value* Right) {
556 printValueLoad(Left);
557 printValueLoad(Right);
558 Out << '\t' << Name << '\n';
559}
560
561
562void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
563 if(Operand)
564 Out << '\t' << Inst << '\t' << Operand << '\n';
565 else
566 Out << '\t' << Inst << '\n';
567}
568
569
570void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
571 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
572 isa<PHINode>(I); ++I) {
573 const PHINode* Phi = cast<PHINode>(I);
574 const Value* Val = Phi->getIncomingValueForBlock(Src);
575 if (isa<UndefValue>(Val)) continue;
576 printValueLoad(Val);
577 printValueSave(Phi);
578 }
579}
580
581
582void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
583 const BasicBlock* TrueBB,
584 const BasicBlock* FalseBB) {
585 if (TrueBB==FalseBB) {
586 // "TrueBB" and "FalseBB" destination equals
587 printPHICopy(CurrBB,TrueBB);
588 printSimpleInstruction("pop");
589 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
590 } else if (FalseBB==NULL) {
591 // If "FalseBB" not used the jump have condition
592 printPHICopy(CurrBB,TrueBB);
593 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
594 } else if (TrueBB==NULL) {
595 // If "TrueBB" not used the jump is unconditional
596 printPHICopy(CurrBB,FalseBB);
597 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
598 } else {
599 // Copy PHI instructions for each block
600 std::string TmpLabel;
601 // Print PHI instructions for "TrueBB"
602 if (isa<PHINode>(TrueBB->begin())) {
603 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
604 printSimpleInstruction("brtrue",TmpLabel.c_str());
605 } else {
606 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
607 }
608 // Print PHI instructions for "FalseBB"
609 if (isa<PHINode>(FalseBB->begin())) {
610 printPHICopy(CurrBB,FalseBB);
611 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
612 } else {
613 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
614 }
615 if (isa<PHINode>(TrueBB->begin())) {
616 // Handle "TrueBB" PHI Copy
617 Out << TmpLabel << ":\n";
618 printPHICopy(CurrBB,TrueBB);
619 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
620 }
621 }
622}
623
624
625void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
626 if (Inst->isUnconditional()) {
627 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
628 } else {
629 printValueLoad(Inst->getCondition());
630 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
631 Inst->getSuccessor(1));
632 }
633}
634
635
636void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
637 const Value* VFalse) {
638 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
639 printValueLoad(VTrue);
640 printValueLoad(Cond);
641 printSimpleInstruction("brtrue",TmpLabel.c_str());
642 printSimpleInstruction("pop");
643 printValueLoad(VFalse);
644 Out << TmpLabel << ":\n";
645}
646
647
648void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000649 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000650 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000651 if (const PointerType* P = dyn_cast<PointerType>(Ty))
652 Ty = P->getElementType();
653 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000654 printSimpleInstruction(Tmp.c_str());
655}
656
657
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000658void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000659 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000660 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000661 printIndirectSave(Val->getType());
662}
663
664
665void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000666 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000667 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000668 if (*postfix.begin()=='u') *postfix.begin() = 'i';
669 postfix = "stind."+postfix;
670 printSimpleInstruction(postfix.c_str());
671}
672
673
674void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000675 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000676 std::string Tmp("");
677 printValueLoad(V);
678 switch (Op) {
679 // Signed
680 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000681 // If sign extending int, convert first from unsigned to signed
682 // with the same bit size - because otherwise we will loose the sign.
683 if (SrcTy) {
684 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
685 printSimpleInstruction(Tmp.c_str());
686 }
Bill Wendling5f544502009-07-14 18:30:04 +0000687 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000688 case Instruction::SIToFP:
689 case Instruction::FPToSI:
690 Tmp = "conv."+getTypePostfix(Ty,false,true);
691 printSimpleInstruction(Tmp.c_str());
692 break;
693 // Unsigned
694 case Instruction::FPTrunc:
695 case Instruction::FPExt:
696 case Instruction::UIToFP:
697 case Instruction::Trunc:
698 case Instruction::ZExt:
699 case Instruction::FPToUI:
700 case Instruction::PtrToInt:
701 case Instruction::IntToPtr:
702 Tmp = "conv."+getTypePostfix(Ty,false);
703 printSimpleInstruction(Tmp.c_str());
704 break;
705 // Do nothing
706 case Instruction::BitCast:
707 // FIXME: meaning that ld*/st* instruction do not change data format.
708 break;
709 default:
710 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000711 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000712 }
713}
714
715
716void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
717 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000718 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000719 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000720 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000721 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000722 for (; I!=E; ++I){
723 Size = 0;
724 const Value* IndexValue = I.getOperand();
725 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
726 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
727 // Offset is the sum of all previous structure fields.
728 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000729 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000730 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000731 printSimpleInstruction("add");
732 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000733 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000734 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000735 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000736 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000737 }
738 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000739 if (!isZeroValue(IndexValue)) {
740 // Constant optimization.
741 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
742 if (C->getValue().isNegative()) {
743 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
744 printSimpleInstruction("sub");
745 continue;
746 } else
747 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000748 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000749 printPtrLoad(Size);
750 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000751 printSimpleInstruction("mul");
752 }
753 printSimpleInstruction("add");
754 }
755 }
756}
757
758
759std::string MSILWriter::getCallSignature(const FunctionType* Ty,
760 const Instruction* Inst,
761 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000762 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000763 if (Ty->isVarArg()) Tmp += "vararg ";
764 // Name and return type.
765 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
766 // Function argument type list.
767 unsigned NumParams = Ty->getNumParams();
768 for (unsigned I = 0; I!=NumParams; ++I) {
769 if (I!=0) Tmp += ",";
770 Tmp += getTypeName(Ty->getParamType(I));
771 }
772 // CLR needs to know the exact amount of parameters received by vararg
773 // function, because caller cleans the stack.
774 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000775 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000776 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
777 // Print variable argument types.
778 unsigned NumOperands = Inst->getNumOperands()-Org;
779 if (NumParams<NumOperands) {
780 if (NumParams!=0) Tmp += ", ";
781 Tmp += "... , ";
782 for (unsigned J = NumParams; J!=NumOperands; ++J) {
783 if (J!=NumParams) Tmp += ", ";
784 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
785 }
786 }
787 }
788 return Tmp+")";
789}
790
791
792void MSILWriter::printFunctionCall(const Value* FnVal,
793 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000794 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000795 std::string Name = "";
796 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
797 Name = getConvModopt(Call->getCallingConv());
798 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
799 Name = getConvModopt(Invoke->getCallingConv());
800 else {
801 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000802 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000803 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000804 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000805 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000806 Name += getValueName(F);
807 printSimpleInstruction("call",
808 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
809 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000810 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000811 const PointerType* PTy = cast<PointerType>(FnVal->getType());
812 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000813 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000814 printValueLoad(FnVal);
815 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
816 }
817}
818
819
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000820void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
821 std::string Name;
822 switch (Inst->getIntrinsicID()) {
823 case Intrinsic::vastart:
824 Name = getValueName(Inst->getOperand(1));
825 Name.insert(Name.length()-1,"$valist");
826 // Obtain the argument handle.
827 printSimpleInstruction("ldloca",Name.c_str());
828 printSimpleInstruction("arglist");
829 printSimpleInstruction("call",
830 "instance void [mscorlib]System.ArgIterator::.ctor"
831 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
832 // Save as pointer type "void*"
833 printValueLoad(Inst->getOperand(1));
834 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000835 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000836 break;
837 case Intrinsic::vaend:
838 // Close argument list handle.
839 printIndirectLoad(Inst->getOperand(1));
840 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
841 break;
842 case Intrinsic::vacopy:
843 // Copy "ArgIterator" valuetype.
844 printIndirectLoad(Inst->getOperand(1));
845 printIndirectLoad(Inst->getOperand(2));
846 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
847 break;
848 default:
849 cerr << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000850 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000851 }
852}
853
854
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000855void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000856 if (isa<IntrinsicInst>(Inst)) {
857 // Handle intrinsic function.
858 printIntrinsicCall(cast<IntrinsicInst>(Inst));
859 } else {
860 // Load arguments to stack and call function.
861 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
862 printValueLoad(Inst->getOperand(I));
863 printFunctionCall(Inst->getOperand(0),Inst);
864 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000865}
866
867
868void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
869 const Value* Right) {
870 switch (Predicate) {
871 case ICmpInst::ICMP_EQ:
872 printBinaryInstruction("ceq",Left,Right);
873 break;
874 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000875 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000876 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000877 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000878 printSimpleInstruction("not");
879 break;
880 case ICmpInst::ICMP_ULE:
881 case ICmpInst::ICMP_SLE:
882 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
883 printBinaryInstruction("ceq",Left,Right);
884 if (Predicate==ICmpInst::ICMP_ULE)
885 printBinaryInstruction("clt.un",Left,Right);
886 else
887 printBinaryInstruction("clt",Left,Right);
888 printSimpleInstruction("or");
889 break;
890 case ICmpInst::ICMP_UGE:
891 case ICmpInst::ICMP_SGE:
892 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
893 printBinaryInstruction("ceq",Left,Right);
894 if (Predicate==ICmpInst::ICMP_UGE)
895 printBinaryInstruction("cgt.un",Left,Right);
896 else
897 printBinaryInstruction("cgt",Left,Right);
898 printSimpleInstruction("or");
899 break;
900 case ICmpInst::ICMP_ULT:
901 printBinaryInstruction("clt.un",Left,Right);
902 break;
903 case ICmpInst::ICMP_SLT:
904 printBinaryInstruction("clt",Left,Right);
905 break;
906 case ICmpInst::ICMP_UGT:
907 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000908 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000909 case ICmpInst::ICMP_SGT:
910 printBinaryInstruction("cgt",Left,Right);
911 break;
912 default:
913 cerr << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000914 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000915 }
916}
917
918
919void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
920 const Value* Right) {
921 // FIXME: Correct comparison
922 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
923 switch (Predicate) {
924 case FCmpInst::FCMP_UGT:
925 // X > Y || llvm_fcmp_uno(X, Y)
926 printBinaryInstruction("cgt",Left,Right);
927 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
928 printSimpleInstruction("or");
929 break;
930 case FCmpInst::FCMP_OGT:
931 // X > Y
932 printBinaryInstruction("cgt",Left,Right);
933 break;
934 case FCmpInst::FCMP_UGE:
935 // X >= Y || llvm_fcmp_uno(X, Y)
936 printBinaryInstruction("ceq",Left,Right);
937 printBinaryInstruction("cgt",Left,Right);
938 printSimpleInstruction("or");
939 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
940 printSimpleInstruction("or");
941 break;
942 case FCmpInst::FCMP_OGE:
943 // X >= Y
944 printBinaryInstruction("ceq",Left,Right);
945 printBinaryInstruction("cgt",Left,Right);
946 printSimpleInstruction("or");
947 break;
948 case FCmpInst::FCMP_ULT:
949 // X < Y || llvm_fcmp_uno(X, Y)
950 printBinaryInstruction("clt",Left,Right);
951 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
952 printSimpleInstruction("or");
953 break;
954 case FCmpInst::FCMP_OLT:
955 // X < Y
956 printBinaryInstruction("clt",Left,Right);
957 break;
958 case FCmpInst::FCMP_ULE:
959 // X <= Y || llvm_fcmp_uno(X, Y)
960 printBinaryInstruction("ceq",Left,Right);
961 printBinaryInstruction("clt",Left,Right);
962 printSimpleInstruction("or");
963 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
964 printSimpleInstruction("or");
965 break;
966 case FCmpInst::FCMP_OLE:
967 // X <= Y
968 printBinaryInstruction("ceq",Left,Right);
969 printBinaryInstruction("clt",Left,Right);
970 printSimpleInstruction("or");
971 break;
972 case FCmpInst::FCMP_UEQ:
973 // X == Y || llvm_fcmp_uno(X, Y)
974 printBinaryInstruction("ceq",Left,Right);
975 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
976 printSimpleInstruction("or");
977 break;
978 case FCmpInst::FCMP_OEQ:
979 // X == Y
980 printBinaryInstruction("ceq",Left,Right);
981 break;
982 case FCmpInst::FCMP_UNE:
983 // X != Y
984 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000985 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000986 printSimpleInstruction("not");
987 break;
988 case FCmpInst::FCMP_ONE:
989 // X != Y && llvm_fcmp_ord(X, Y)
990 printBinaryInstruction("ceq",Left,Right);
991 printSimpleInstruction("not");
992 break;
993 case FCmpInst::FCMP_ORD:
994 // return X == X && Y == Y
995 printBinaryInstruction("ceq",Left,Left);
996 printBinaryInstruction("ceq",Right,Right);
997 printSimpleInstruction("or");
998 break;
999 case FCmpInst::FCMP_UNO:
1000 // X != X || Y != Y
1001 printBinaryInstruction("ceq",Left,Left);
1002 printSimpleInstruction("not");
1003 printBinaryInstruction("ceq",Right,Right);
1004 printSimpleInstruction("not");
1005 printSimpleInstruction("or");
1006 break;
1007 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001008 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001009 }
1010}
1011
1012
1013void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1014 std::string Label = "leave$normal_"+utostr(getUniqID());
1015 Out << ".try {\n";
1016 // Load arguments
1017 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1018 printValueLoad(Inst->getOperand(I));
1019 // Print call instruction
1020 printFunctionCall(Inst->getOperand(0),Inst);
1021 // Save function result and leave "try" block
1022 printValueSave(Inst);
1023 printSimpleInstruction("leave",Label.c_str());
1024 Out << "}\n";
1025 Out << "catch [mscorlib]System.Exception {\n";
1026 // Redirect to unwind block
1027 printSimpleInstruction("pop");
1028 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1029 Out << "}\n" << Label << ":\n";
1030 // Redirect to continue block
1031 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1032}
1033
1034
1035void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1036 // FIXME: Emulate with IL "switch" instruction
1037 // Emulate = if () else if () else if () else ...
1038 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1039 printValueLoad(Inst->getCondition());
1040 printValueLoad(Inst->getCaseValue(I));
1041 printSimpleInstruction("ceq");
1042 // Condition jump to successor block
1043 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1044 }
1045 // Jump to default block
1046 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1047}
1048
1049
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001050void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1051 printIndirectLoad(Inst->getOperand(0));
1052 printSimpleInstruction("call",
1053 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1054 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001055 std::string Name =
1056 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001057 printSimpleInstruction(Name.c_str());
1058}
1059
1060
1061void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001062 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001063 // Constant optimization.
1064 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1065 printPtrLoad(CInt->getZExtValue()*Size);
1066 } else {
1067 printPtrLoad(Size);
1068 printValueLoad(Inst->getOperand(0));
1069 printSimpleInstruction("mul");
1070 }
1071 printSimpleInstruction("localloc");
1072}
1073
1074
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001075void MSILWriter::printInstruction(const Instruction* Inst) {
1076 const Value *Left = 0, *Right = 0;
1077 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1078 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1079 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001080 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001081 switch (Inst->getOpcode()) {
1082 // Terminator
1083 case Instruction::Ret:
1084 if (Inst->getNumOperands()) {
1085 printValueLoad(Left);
1086 printSimpleInstruction("ret");
1087 } else
1088 printSimpleInstruction("ret");
1089 break;
1090 case Instruction::Br:
1091 printBranchInstruction(cast<BranchInst>(Inst));
1092 break;
1093 // Binary
1094 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001095 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001096 printBinaryInstruction("add",Left,Right);
1097 break;
1098 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001099 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001100 printBinaryInstruction("sub",Left,Right);
1101 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001102 case Instruction::Mul:
1103 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001104 printBinaryInstruction("mul",Left,Right);
1105 break;
1106 case Instruction::UDiv:
1107 printBinaryInstruction("div.un",Left,Right);
1108 break;
1109 case Instruction::SDiv:
1110 case Instruction::FDiv:
1111 printBinaryInstruction("div",Left,Right);
1112 break;
1113 case Instruction::URem:
1114 printBinaryInstruction("rem.un",Left,Right);
1115 break;
1116 case Instruction::SRem:
1117 case Instruction::FRem:
1118 printBinaryInstruction("rem",Left,Right);
1119 break;
1120 // Binary Condition
1121 case Instruction::ICmp:
1122 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1123 break;
1124 case Instruction::FCmp:
1125 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1126 break;
1127 // Bitwise Binary
1128 case Instruction::And:
1129 printBinaryInstruction("and",Left,Right);
1130 break;
1131 case Instruction::Or:
1132 printBinaryInstruction("or",Left,Right);
1133 break;
1134 case Instruction::Xor:
1135 printBinaryInstruction("xor",Left,Right);
1136 break;
1137 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001138 printValueLoad(Left);
1139 printValueLoad(Right);
1140 printSimpleInstruction("conv.i4");
1141 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001142 break;
1143 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001144 printValueLoad(Left);
1145 printValueLoad(Right);
1146 printSimpleInstruction("conv.i4");
1147 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001148 break;
1149 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001150 printValueLoad(Left);
1151 printValueLoad(Right);
1152 printSimpleInstruction("conv.i4");
1153 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001154 break;
1155 case Instruction::Select:
1156 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1157 break;
1158 case Instruction::Load:
1159 printIndirectLoad(Inst->getOperand(0));
1160 break;
1161 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001162 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001163 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001164 case Instruction::SExt:
1165 printCastInstruction(Inst->getOpcode(),Left,
1166 cast<CastInst>(Inst)->getDestTy(),
1167 cast<CastInst>(Inst)->getSrcTy());
1168 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001169 case Instruction::Trunc:
1170 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001171 case Instruction::FPTrunc:
1172 case Instruction::FPExt:
1173 case Instruction::UIToFP:
1174 case Instruction::SIToFP:
1175 case Instruction::FPToUI:
1176 case Instruction::FPToSI:
1177 case Instruction::PtrToInt:
1178 case Instruction::IntToPtr:
1179 case Instruction::BitCast:
1180 printCastInstruction(Inst->getOpcode(),Left,
1181 cast<CastInst>(Inst)->getDestTy());
1182 break;
1183 case Instruction::GetElementPtr:
1184 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1185 gep_type_end(Inst));
1186 break;
1187 case Instruction::Call:
1188 printCallInstruction(cast<CallInst>(Inst));
1189 break;
1190 case Instruction::Invoke:
1191 printInvokeInstruction(cast<InvokeInst>(Inst));
1192 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001193 case Instruction::Unwind:
1194 printSimpleInstruction("newobj",
1195 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001196 printSimpleInstruction("throw");
1197 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001198 case Instruction::Switch:
1199 printSwitchInstruction(cast<SwitchInst>(Inst));
1200 break;
1201 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001202 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001203 break;
1204 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001205 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001206 break;
1207 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001208 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001209 break;
1210 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001211 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1212 printSimpleInstruction("newobj",
1213 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001214 printSimpleInstruction("throw");
1215 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001216 case Instruction::VAArg:
1217 printVAArgInstruction(cast<VAArgInst>(Inst));
1218 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001219 default:
1220 cerr << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001221 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001222 }
1223}
1224
1225
1226void MSILWriter::printLoop(const Loop* L) {
1227 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1228 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1229 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1230 BasicBlock* BB = blocks[I];
1231 Loop* BBLoop = LInfo->getLoopFor(BB);
1232 if (BBLoop == L)
1233 printBasicBlock(BB);
1234 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1235 printLoop(BBLoop);
1236 }
1237 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1238}
1239
1240
1241void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1242 Out << getLabelName(BB) << ":\n";
1243 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1244 const Instruction* Inst = I;
1245 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001246 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001247 // Do not handle PHI instruction in current block
1248 if (Inst->getOpcode()==Instruction::PHI) continue;
1249 // Print instruction
1250 printInstruction(Inst);
1251 // Save result
1252 if (Inst->getType()!=Type::VoidTy) {
1253 // Do not save value after invoke, it done in "try" block
1254 if (Inst->getOpcode()==Instruction::Invoke) continue;
1255 printValueSave(Inst);
1256 }
1257 }
1258}
1259
1260
1261void MSILWriter::printLocalVariables(const Function& F) {
1262 std::string Name;
1263 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001264 std::set<const Value*> Printed;
1265 const Value* VaList = NULL;
1266 unsigned StackDepth = 8;
1267 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001268 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001269 if (I->getOpcode()==Instruction::Call ||
1270 I->getOpcode()==Instruction::Invoke) {
1271 // Test stack depth.
1272 if (StackDepth<I->getNumOperands())
1273 StackDepth = I->getNumOperands();
1274 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001275 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1276 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001277 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001278 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001279 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001280 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001281 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001282 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001283 Ty = I->getType();
1284 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001285 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1286 }
1287 // Test on 'va_list' variable
1288 bool isVaList = false;
1289 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1290 // "va_list" as "va_arg" instruction operand.
1291 isVaList = true;
1292 VaList = VaInst->getOperand(0);
1293 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1294 // "va_list" as intrinsic function operand.
1295 switch (Inst->getIntrinsicID()) {
1296 case Intrinsic::vastart:
1297 case Intrinsic::vaend:
1298 case Intrinsic::vacopy:
1299 isVaList = true;
1300 VaList = Inst->getOperand(1);
1301 break;
1302 default:
1303 isVaList = false;
1304 }
1305 }
1306 // Print "va_list" variable.
1307 if (isVaList && Printed.insert(VaList).second) {
1308 Name = getValueName(VaList);
1309 Name.insert(Name.length()-1,"$valist");
1310 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1311 << Name << ")\n";
1312 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001313 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001314 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001315}
1316
1317
1318void MSILWriter::printFunctionBody(const Function& F) {
1319 // Print body
1320 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1321 if (Loop *L = LInfo->getLoopFor(I)) {
1322 if (L->getHeader()==I && L->getParentLoop()==0)
1323 printLoop(L);
1324 } else {
1325 printBasicBlock(I);
1326 }
1327 }
1328}
1329
1330
1331void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1332 const Value *left = 0, *right = 0;
1333 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1334 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1335 // Print instruction
1336 switch (CE->getOpcode()) {
1337 case Instruction::Trunc:
1338 case Instruction::ZExt:
1339 case Instruction::SExt:
1340 case Instruction::FPTrunc:
1341 case Instruction::FPExt:
1342 case Instruction::UIToFP:
1343 case Instruction::SIToFP:
1344 case Instruction::FPToUI:
1345 case Instruction::FPToSI:
1346 case Instruction::PtrToInt:
1347 case Instruction::IntToPtr:
1348 case Instruction::BitCast:
1349 printCastInstruction(CE->getOpcode(),left,CE->getType());
1350 break;
1351 case Instruction::GetElementPtr:
1352 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1353 break;
1354 case Instruction::ICmp:
1355 printICmpInstruction(CE->getPredicate(),left,right);
1356 break;
1357 case Instruction::FCmp:
1358 printFCmpInstruction(CE->getPredicate(),left,right);
1359 break;
1360 case Instruction::Select:
1361 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1362 break;
1363 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001364 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001365 printBinaryInstruction("add",left,right);
1366 break;
1367 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001368 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001369 printBinaryInstruction("sub",left,right);
1370 break;
1371 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001372 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001373 printBinaryInstruction("mul",left,right);
1374 break;
1375 case Instruction::UDiv:
1376 printBinaryInstruction("div.un",left,right);
1377 break;
1378 case Instruction::SDiv:
1379 case Instruction::FDiv:
1380 printBinaryInstruction("div",left,right);
1381 break;
1382 case Instruction::URem:
1383 printBinaryInstruction("rem.un",left,right);
1384 break;
1385 case Instruction::SRem:
1386 case Instruction::FRem:
1387 printBinaryInstruction("rem",left,right);
1388 break;
1389 case Instruction::And:
1390 printBinaryInstruction("and",left,right);
1391 break;
1392 case Instruction::Or:
1393 printBinaryInstruction("or",left,right);
1394 break;
1395 case Instruction::Xor:
1396 printBinaryInstruction("xor",left,right);
1397 break;
1398 case Instruction::Shl:
1399 printBinaryInstruction("shl",left,right);
1400 break;
1401 case Instruction::LShr:
1402 printBinaryInstruction("shr.un",left,right);
1403 break;
1404 case Instruction::AShr:
1405 printBinaryInstruction("shr",left,right);
1406 break;
1407 default:
1408 cerr << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001409 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001410 }
1411}
1412
1413
1414void MSILWriter::printStaticInitializerList() {
1415 // List of global variables with uninitialized fields.
1416 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1417 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1418 ++VarI) {
1419 const std::vector<StaticInitializer>& InitList = VarI->second;
1420 if (InitList.empty()) continue;
1421 // For each uninitialized field.
1422 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1423 E = InitList.end(); I!=E; ++I) {
1424 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001425 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1426 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001427 // Load variable address
1428 printValueLoad(VarI->first);
1429 // Add offset
1430 if (I->offset!=0) {
1431 printPtrLoad(I->offset);
1432 printSimpleInstruction("add");
1433 }
1434 // Load value
1435 printConstantExpr(CE);
1436 // Save result at offset
1437 std::string postfix = getTypePostfix(CE->getType(),true);
1438 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1439 postfix = "stind."+postfix;
1440 printSimpleInstruction(postfix.c_str());
1441 } else {
1442 cerr << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001443 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001444 }
1445 }
1446 }
1447}
1448
1449
1450void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001451 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001452 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001453 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001454 if (F.isVarArg()) Out << "vararg ";
1455 Out << getTypeName(F.getReturnType(),isSigned) <<
1456 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1457 // Arguments
1458 Out << "\t(";
1459 unsigned ArgIdx = 1;
1460 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1461 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001462 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001463 if (I!=F.arg_begin()) Out << ", ";
1464 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1465 }
1466 Out << ") cil managed\n";
1467 // Body
1468 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001469 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001470 printFunctionBody(F);
1471 Out << "}\n";
1472}
1473
1474
1475void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1476 std::string Name;
1477 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001478 for (std::set<const Type*>::const_iterator
1479 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1480 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001481 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1482 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001483 // Type with no need to declare.
1484 else continue;
1485 // Print not duplicated type
1486 if (Printed.insert(Ty).second) {
1487 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001488 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001489 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001490 }
1491 }
1492}
1493
1494
1495unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1496 unsigned int N = Ty->getPrimitiveSizeInBits();
1497 assert(N!=0 && "Invalid type in getBitWidth()");
1498 switch (N) {
1499 case 1:
1500 case 8:
1501 case 16:
1502 case 32:
1503 case 64:
1504 return N;
1505 default:
1506 cerr << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001507 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001508 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001509 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001510}
1511
1512
1513void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1514 uint64_t TySize = 0;
1515 const Type* Ty = C->getType();
1516 // Print zero initialized constant.
1517 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001518 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001519 Offset += TySize;
1520 Out << "int8 (0) [" << TySize << "]";
1521 return;
1522 }
1523 // Print constant initializer
1524 switch (Ty->getTypeID()) {
1525 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001526 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001527 const ConstantInt* Int = cast<ConstantInt>(C);
1528 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1529 break;
1530 }
1531 case Type::FloatTyID:
1532 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001533 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001534 const ConstantFP* FP = cast<ConstantFP>(C);
1535 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001536 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001537 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001538 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001539 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001540 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001541 break;
1542 }
1543 case Type::ArrayTyID:
1544 case Type::VectorTyID:
1545 case Type::StructTyID:
1546 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1547 if (I!=0) Out << ",\n";
1548 printStaticConstant(C->getOperand(I),Offset);
1549 }
1550 break;
1551 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001552 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001553 // Initialize with global variable address
1554 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1555 std::string name = getValueName(G);
1556 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1557 } else {
1558 // Dynamic initialization
1559 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1560 InitListPtr->push_back(StaticInitializer(C,Offset));
1561 // Null pointer initialization
1562 if (TySize==4) Out << "int32 (0)";
1563 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001564 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001565 }
1566 break;
1567 default:
1568 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001569 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001570 }
1571 // Increase offset.
1572 Offset += TySize;
1573}
1574
1575
1576void MSILWriter::printStaticInitializer(const Constant* C,
1577 const std::string& Name) {
1578 switch (C->getType()->getTypeID()) {
1579 case Type::IntegerTyID:
1580 case Type::FloatTyID:
1581 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001582 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001583 break;
1584 case Type::ArrayTyID:
1585 case Type::VectorTyID:
1586 case Type::StructTyID:
1587 case Type::PointerTyID:
1588 Out << getTypeName(C->getType());
1589 break;
1590 default:
1591 cerr << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001592 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001593 }
1594 // Print initializer
1595 std::string label = Name;
1596 label.insert(label.length()-1,"$data");
1597 Out << Name << " at " << label << '\n';
1598 Out << ".data " << label << " = {\n";
1599 uint64_t offset = 0;
1600 printStaticConstant(C,offset);
1601 Out << "\n}\n\n";
1602}
1603
1604
1605void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1606 const Constant* C = G->getInitializer();
1607 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1608 InitListPtr = 0;
1609 else
1610 InitListPtr = &StaticInitList[G];
1611 printStaticInitializer(C,getValueName(G));
1612}
1613
1614
1615void MSILWriter::printGlobalVariables() {
1616 if (ModulePtr->global_empty()) return;
1617 Module::global_iterator I,E;
1618 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1619 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001620 Out << ".field static " << (I->isDeclaration() ? "public " :
1621 "private ");
1622 if (I->isDeclaration()) {
1623 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1624 } else
1625 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001626 }
1627}
1628
1629
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001630const char* MSILWriter::getLibraryName(const Function* F) {
1631 return getLibraryForSymbol(F->getName().c_str(), true, F->getCallingConv());
1632}
1633
1634
1635const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001636 return getLibraryForSymbol(Mang->getMangledName(GV).c_str(), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001637}
1638
1639
1640const char* MSILWriter::getLibraryForSymbol(const char* Name, bool isFunction,
1641 unsigned CallingConv) {
1642 // TODO: Read *.def file with function and libraries definitions.
1643 return "MSVCRT.DLL";
1644}
1645
1646
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001647void MSILWriter::printExternals() {
1648 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001649 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001650 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1651 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001652 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001653 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001654 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001655 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001656 std::string Sig =
1657 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1658 Out << ".method static hidebysig pinvokeimpl(\""
1659 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001660 }
1661 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001662 // External variables and static initialization.
1663 Out <<
1664 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1665 " native int LoadLibrary(string) preservesig {}\n"
1666 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1667 " native int GetProcAddress(native int, string) preservesig {}\n";
1668 Out <<
1669 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1670 " managed cil\n{\n"
1671 "\tldarg\tlib\n"
1672 "\tcall\tnative int LoadLibrary(string)\n"
1673 "\tldarg\tsym\n"
1674 "\tcall\tnative int GetProcAddress(native int,string)\n"
1675 "\tdup\n"
1676 "\tbrtrue\tL_01\n"
1677 "\tldstr\t\"Can no import variable\"\n"
1678 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1679 "\tthrow\n"
1680 "L_01:\n"
1681 "\tret\n"
1682 "}\n\n"
1683 ".method static private void $MSIL_Init() managed cil\n{\n";
1684 printStaticInitializerList();
1685 // Foreach global variable.
1686 for (Module::global_iterator I = ModulePtr->global_begin(),
1687 E = ModulePtr->global_end(); I!=E; ++I) {
1688 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1689 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1690 std::string Label = "not_null$_"+utostr(getUniqID());
1691 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1692 printSimpleInstruction("ldsflda",Tmp.c_str());
1693 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001694 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001695 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1696 printIndirectSave(I->getType());
1697 }
1698 printSimpleInstruction("ret");
1699 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001700}
1701
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001702
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001703//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001704// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001705//===----------------------------------------------------------------------===//
1706
David Greene71847812009-07-14 20:18:05 +00001707bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1708 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001709 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001710 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001711{
1712 if (FileType != TargetMachine::AssemblyFile) return true;
1713 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001714 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001715 PM.add(createLowerAllocationsPass(true));
1716 // FIXME: Handle switch trougth native IL instruction "switch"
1717 PM.add(createLowerSwitchPass());
1718 PM.add(createCFGSimplificationPass());
1719 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1720 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001721 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001722 return false;
1723}