blob: 0a837798f6f8f29ecb14138dfa8a6197c0e5a04d [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"
Daniel Dunbar0c795d62009-07-25 06:49:55 +000025#include "llvm/Target/TargetRegistry.h"
Anton Korobeynikov099883f2007-03-21 21:38:25 +000026#include "llvm/Transforms/Scalar.h"
27#include "llvm/ADT/StringExtras.h"
Gordon Henriksence224772008-01-07 01:30:38 +000028#include "llvm/CodeGen/Passes.h"
Nick Lewycky92fbbc72009-07-26 08:16:51 +000029using namespace llvm;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000030
Nick Lewycky92fbbc72009-07-26 08:16:51 +000031namespace llvm {
Anton Korobeynikov099883f2007-03-21 21:38:25 +000032 // TargetMachine for the MSIL
33 struct VISIBILITY_HIDDEN MSILTarget : public TargetMachine {
Daniel Dunbar214e2232009-08-04 04:02:45 +000034 MSILTarget(const Target &T, const std::string &TT, const std::string &FS)
35 : TargetMachine(T) {}
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
Daniel Dunbard1a919e2009-08-03 17:40:25 +000043 virtual const TargetData *getTargetData() const { return 0; }
Anton Korobeynikov099883f2007-03-21 21:38:25 +000044 };
45}
46
Daniel Dunbar0c795d62009-07-25 06:49:55 +000047extern "C" void LLVMInitializeMSILTarget() {
48 // Register the target.
Daniel Dunbar214e2232009-08-04 04:02:45 +000049 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000050}
Douglas Gregor1555a232009-06-16 20:12:29 +000051
Anton Korobeynikov099883f2007-03-21 21:38:25 +000052bool MSILModule::runOnModule(Module &M) {
53 ModulePtr = &M;
54 TD = &getAnalysis<TargetData>();
55 bool Changed = false;
56 // Find named types.
57 TypeSymbolTable& Table = M.getTypeSymbolTable();
58 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
59 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
60 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
61 Table.remove(I++);
62 else {
63 std::set<const Type *>::iterator T = Types.find(I->second);
64 if (T==Types.end())
65 Table.remove(I++);
66 else {
67 Types.erase(T);
68 ++I;
69 }
70 }
71 }
72 // Find unnamed types.
73 unsigned RenameCounter = 0;
74 for (std::set<const Type *>::const_iterator I = Types.begin(),
75 E = Types.end(); I!=E; ++I)
76 if (const StructType *STy = dyn_cast<StructType>(*I)) {
77 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
78 ++RenameCounter;
79 Changed = true;
80 }
81 // Pointer for FunctionPass.
82 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
83 return Changed;
84}
85
Devang Patel19974732007-05-03 01:11:54 +000086char MSILModule::ID = 0;
87char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000088
89bool MSILWriter::runOnFunction(Function &F) {
90 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000091
92 // Do not codegen any 'available_externally' functions at all, they have
93 // definitions outside the translation unit.
94 if (F.hasAvailableExternallyLinkage())
95 return false;
96
Anton Korobeynikov099883f2007-03-21 21:38:25 +000097 LInfo = &getAnalysis<LoopInfo>();
98 printFunction(F);
99 return false;
100}
101
102
103bool MSILWriter::doInitialization(Module &M) {
104 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000105 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000106 Out << ".assembly extern mscorlib {}\n";
107 Out << ".assembly MSIL {}\n\n";
108 Out << "// External\n";
109 printExternals();
110 Out << "// Declarations\n";
111 printDeclarations(M.getTypeSymbolTable());
112 Out << "// Definitions\n";
113 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000114 Out << "// Startup code\n";
115 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000116 return false;
117}
118
119
120bool MSILWriter::doFinalization(Module &M) {
121 delete Mang;
122 return false;
123}
124
125
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000126void MSILWriter::printModuleStartup() {
127 Out <<
128 ".method static public int32 $MSIL_Startup() {\n"
129 "\t.entrypoint\n"
130 "\t.locals (native int i)\n"
131 "\t.locals (native int argc)\n"
132 "\t.locals (native int ptr)\n"
133 "\t.locals (void* argv)\n"
134 "\t.locals (string[] args)\n"
135 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
136 "\tdup\n"
137 "\tstloc\targs\n"
138 "\tldlen\n"
139 "\tconv.i4\n"
140 "\tdup\n"
141 "\tstloc\targc\n";
142 printPtrLoad(TD->getPointerSize());
143 Out <<
144 "\tmul\n"
145 "\tlocalloc\n"
146 "\tstloc\targv\n"
147 "\tldc.i4.0\n"
148 "\tstloc\ti\n"
149 "L_01:\n"
150 "\tldloc\ti\n"
151 "\tldloc\targc\n"
152 "\tceq\n"
153 "\tbrtrue\tL_02\n"
154 "\tldloc\targs\n"
155 "\tldloc\ti\n"
156 "\tldelem.ref\n"
157 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
158 "StringToHGlobalAnsi(string)\n"
159 "\tstloc\tptr\n"
160 "\tldloc\targv\n"
161 "\tldloc\ti\n";
162 printPtrLoad(TD->getPointerSize());
163 Out <<
164 "\tmul\n"
165 "\tadd\n"
166 "\tldloc\tptr\n"
167 "\tstind.i\n"
168 "\tldloc\ti\n"
169 "\tldc.i4.1\n"
170 "\tadd\n"
171 "\tstloc\ti\n"
172 "\tbr\tL_01\n"
173 "L_02:\n"
174 "\tcall void $MSIL_Init()\n";
175
176 // Call user 'main' function.
177 const Function* F = ModulePtr->getFunction("main");
178 if (!F || F->isDeclaration()) {
179 Out << "\tldc.i4.0\n\tret\n}\n";
180 return;
181 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000182 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000183 std::string Args("");
184 Function::const_arg_iterator Arg1,Arg2;
185
186 switch (F->arg_size()) {
187 case 0:
188 BadSig = false;
189 break;
190 case 1:
191 Arg1 = F->arg_begin();
192 if (Arg1->getType()->isInteger()) {
193 Out << "\tldloc\targc\n";
194 Args = getTypeName(Arg1->getType());
195 BadSig = false;
196 }
197 break;
198 case 2:
199 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
200 if (Arg1->getType()->isInteger() &&
201 Arg2->getType()->getTypeID() == Type::PointerTyID) {
202 Out << "\tldloc\targc\n\tldloc\targv\n";
203 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
204 BadSig = false;
205 }
206 break;
207 default:
208 BadSig = true;
209 }
210
211 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000212 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000213 Out << "\tldc.i4.0\n";
214 } else {
215 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
216 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
217 if (RetVoid)
218 Out << "\tldc.i4.0\n";
219 else
220 Out << "\tconv.i4\n";
221 }
222 Out << "\tret\n}\n";
223}
224
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000225bool MSILWriter::isZeroValue(const Value* V) {
226 if (const Constant *C = dyn_cast<Constant>(V))
227 return C->isNullValue();
228 return false;
229}
230
231
232std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000233 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000234 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000235 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000236 else {
237 unsigned &No = AnonValueNumbers[V];
238 if (No == 0) No = ++NextAnonValueNumber;
239 Name = "tmp" + utostr(No);
240 }
241
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000242 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000243 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000244}
245
246
247std::string MSILWriter::getLabelName(const std::string& Name) {
248 if (Name.find('.')!=std::string::npos) {
249 std::string Tmp(Name);
250 // Replace unaccepable characters in the label name.
251 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
252 if (*I=='.') *I = '@';
253 return Tmp;
254 }
255 return Name;
256}
257
258
259std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000260 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000261 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000262 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000263 else {
264 unsigned &No = AnonValueNumbers[V];
265 if (No == 0) No = ++NextAnonValueNumber;
266 Name = "tmp" + utostr(No);
267 }
268
269 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000270}
271
272
273std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
274 switch (CallingConvID) {
275 case CallingConv::C:
276 case CallingConv::Cold:
277 case CallingConv::Fast:
278 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
279 case CallingConv::X86_FastCall:
280 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
281 case CallingConv::X86_StdCall:
282 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
283 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000284 errs() << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000285 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000286 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000287 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000288}
289
290
291std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
292 std::string Tmp = "";
293 const Type* ElemTy = Ty;
294 assert(Ty->getTypeID()==TyID && "Invalid type passed");
295 // Walk trought array element types.
296 for (;;) {
297 // Multidimensional array.
298 if (ElemTy->getTypeID()==TyID) {
299 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
300 Tmp += utostr(ATy->getNumElements());
301 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
302 Tmp += utostr(VTy->getNumElements());
303 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
304 }
305 // Base element type found.
306 if (ElemTy->getTypeID()!=TyID) break;
307 Tmp += ",";
308 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000309 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000310}
311
312
313std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
314 unsigned NumBits = 0;
315 switch (Ty->getTypeID()) {
316 case Type::VoidTyID:
317 return "void ";
318 case Type::IntegerTyID:
319 NumBits = getBitWidth(Ty);
320 if(NumBits==1)
321 return "bool ";
322 if (!isSigned)
323 return "unsigned int"+utostr(NumBits)+" ";
324 return "int"+utostr(NumBits)+" ";
325 case Type::FloatTyID:
326 return "float32 ";
327 case Type::DoubleTyID:
328 return "float64 ";
329 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000330 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000331 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000332 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000333 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000334}
335
336
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000337std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
338 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000339 if (Ty->isPrimitiveType() || Ty->isInteger())
340 return getPrimitiveTypeName(Ty,isSigned);
341 // FIXME: "OpaqueType" support
342 switch (Ty->getTypeID()) {
343 case Type::PointerTyID:
344 return "void* ";
345 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000346 if (isNested)
347 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000348 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
349 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000350 if (isNested)
351 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000352 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
353 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000354 if (isNested)
355 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000356 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
357 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000358 errs() << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000359 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000360 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000361 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000362}
363
364
365MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
366 // Function argument
367 if (isa<Argument>(V))
368 return ArgumentVT;
369 // Function
370 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000371 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000372 // Variable
373 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000374 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000375 // Constant
376 else if (isa<Constant>(V))
377 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
378 // Local variable
379 return LocalVT;
380}
381
382
383std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
384 bool isSigned) {
385 unsigned NumBits = 0;
386 switch (Ty->getTypeID()) {
387 // Integer constant, expanding for stack operations.
388 case Type::IntegerTyID:
389 NumBits = getBitWidth(Ty);
390 // Expand integer value to "int32" or "int64".
391 if (Expand) return (NumBits<=32 ? "i4" : "i8");
392 if (NumBits==1) return "i1";
393 return (isSigned ? "i" : "u")+utostr(NumBits/8);
394 // Float constant.
395 case Type::FloatTyID:
396 return "r4";
397 case Type::DoubleTyID:
398 return "r8";
399 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000400 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000401 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000402 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000403 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000404 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000405 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000406}
407
408
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000409void MSILWriter::printConvToPtr() {
410 switch (ModulePtr->getPointerSize()) {
411 case Module::Pointer32:
412 printSimpleInstruction("conv.u4");
413 break;
414 case Module::Pointer64:
415 printSimpleInstruction("conv.u8");
416 break;
417 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000418 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000419 }
420}
421
422
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000423void MSILWriter::printPtrLoad(uint64_t N) {
424 switch (ModulePtr->getPointerSize()) {
425 case Module::Pointer32:
426 printSimpleInstruction("ldc.i4",utostr(N).c_str());
427 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000428 if (!isUInt32(N)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000429 errs() << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000430 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000431 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000432 break;
433 case Module::Pointer64:
434 printSimpleInstruction("ldc.i8",utostr(N).c_str());
435 break;
436 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000437 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000438 }
439}
440
441
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000442void MSILWriter::printValuePtrLoad(const Value* V) {
443 printValueLoad(V);
444 printConvToPtr();
445}
446
447
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000448void MSILWriter::printConstLoad(const Constant* C) {
449 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
450 // Integer constant
451 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
452 if (CInt->isMinValue(true))
453 Out << CInt->getSExtValue();
454 else
455 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000456 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000457 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000458 uint64_t X;
459 unsigned Size;
460 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000461 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000462 Size = 4;
463 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000464 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000465 Size = 8;
466 }
467 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
468 } else if (isa<UndefValue>(C)) {
469 // Undefined constant value = NULL.
470 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000471 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000472 errs() << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000473 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000474 }
475 Out << '\n';
476}
477
478
479void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000480 MSILWriter::ValueType Location = getValueLocation(V);
481 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000482 // Global variable or function address.
483 case GlobalVT:
484 case InternalVT:
485 if (const Function* F = dyn_cast<Function>(V)) {
486 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
487 printSimpleInstruction("ldftn",
488 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
489 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000490 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000491 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000492 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
493 Tmp = "void* "+getValueName(V);
494 printSimpleInstruction("ldsfld",Tmp.c_str());
495 } else {
496 Tmp = getTypeName(ElemTy)+getValueName(V);
497 printSimpleInstruction("ldsflda",Tmp.c_str());
498 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000499 }
500 break;
501 // Function argument.
502 case ArgumentVT:
503 printSimpleInstruction("ldarg",getValueName(V).c_str());
504 break;
505 // Local function variable.
506 case LocalVT:
507 printSimpleInstruction("ldloc",getValueName(V).c_str());
508 break;
509 // Constant value.
510 case ConstVT:
511 if (isa<ConstantPointerNull>(V))
512 printPtrLoad(0);
513 else
514 printConstLoad(cast<Constant>(V));
515 break;
516 // Constant expression.
517 case ConstExprVT:
518 printConstantExpr(cast<ConstantExpr>(V));
519 break;
520 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000521 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000522 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000523 }
524}
525
526
527void MSILWriter::printValueSave(const Value* V) {
528 switch (getValueLocation(V)) {
529 case ArgumentVT:
530 printSimpleInstruction("starg",getValueName(V).c_str());
531 break;
532 case LocalVT:
533 printSimpleInstruction("stloc",getValueName(V).c_str());
534 break;
535 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000536 errs() << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000537 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000538 }
539}
540
541
542void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
543 const Value* Right) {
544 printValueLoad(Left);
545 printValueLoad(Right);
546 Out << '\t' << Name << '\n';
547}
548
549
550void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
551 if(Operand)
552 Out << '\t' << Inst << '\t' << Operand << '\n';
553 else
554 Out << '\t' << Inst << '\n';
555}
556
557
558void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
559 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
560 isa<PHINode>(I); ++I) {
561 const PHINode* Phi = cast<PHINode>(I);
562 const Value* Val = Phi->getIncomingValueForBlock(Src);
563 if (isa<UndefValue>(Val)) continue;
564 printValueLoad(Val);
565 printValueSave(Phi);
566 }
567}
568
569
570void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
571 const BasicBlock* TrueBB,
572 const BasicBlock* FalseBB) {
573 if (TrueBB==FalseBB) {
574 // "TrueBB" and "FalseBB" destination equals
575 printPHICopy(CurrBB,TrueBB);
576 printSimpleInstruction("pop");
577 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
578 } else if (FalseBB==NULL) {
579 // If "FalseBB" not used the jump have condition
580 printPHICopy(CurrBB,TrueBB);
581 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
582 } else if (TrueBB==NULL) {
583 // If "TrueBB" not used the jump is unconditional
584 printPHICopy(CurrBB,FalseBB);
585 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
586 } else {
587 // Copy PHI instructions for each block
588 std::string TmpLabel;
589 // Print PHI instructions for "TrueBB"
590 if (isa<PHINode>(TrueBB->begin())) {
591 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
592 printSimpleInstruction("brtrue",TmpLabel.c_str());
593 } else {
594 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
595 }
596 // Print PHI instructions for "FalseBB"
597 if (isa<PHINode>(FalseBB->begin())) {
598 printPHICopy(CurrBB,FalseBB);
599 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
600 } else {
601 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
602 }
603 if (isa<PHINode>(TrueBB->begin())) {
604 // Handle "TrueBB" PHI Copy
605 Out << TmpLabel << ":\n";
606 printPHICopy(CurrBB,TrueBB);
607 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
608 }
609 }
610}
611
612
613void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
614 if (Inst->isUnconditional()) {
615 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
616 } else {
617 printValueLoad(Inst->getCondition());
618 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
619 Inst->getSuccessor(1));
620 }
621}
622
623
624void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
625 const Value* VFalse) {
626 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
627 printValueLoad(VTrue);
628 printValueLoad(Cond);
629 printSimpleInstruction("brtrue",TmpLabel.c_str());
630 printSimpleInstruction("pop");
631 printValueLoad(VFalse);
632 Out << TmpLabel << ":\n";
633}
634
635
636void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000637 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000638 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000639 if (const PointerType* P = dyn_cast<PointerType>(Ty))
640 Ty = P->getElementType();
641 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000642 printSimpleInstruction(Tmp.c_str());
643}
644
645
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000646void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000647 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000648 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000649 printIndirectSave(Val->getType());
650}
651
652
653void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000654 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000655 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000656 if (*postfix.begin()=='u') *postfix.begin() = 'i';
657 postfix = "stind."+postfix;
658 printSimpleInstruction(postfix.c_str());
659}
660
661
662void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000663 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000664 std::string Tmp("");
665 printValueLoad(V);
666 switch (Op) {
667 // Signed
668 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000669 // If sign extending int, convert first from unsigned to signed
670 // with the same bit size - because otherwise we will loose the sign.
671 if (SrcTy) {
672 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
673 printSimpleInstruction(Tmp.c_str());
674 }
Bill Wendling5f544502009-07-14 18:30:04 +0000675 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000676 case Instruction::SIToFP:
677 case Instruction::FPToSI:
678 Tmp = "conv."+getTypePostfix(Ty,false,true);
679 printSimpleInstruction(Tmp.c_str());
680 break;
681 // Unsigned
682 case Instruction::FPTrunc:
683 case Instruction::FPExt:
684 case Instruction::UIToFP:
685 case Instruction::Trunc:
686 case Instruction::ZExt:
687 case Instruction::FPToUI:
688 case Instruction::PtrToInt:
689 case Instruction::IntToPtr:
690 Tmp = "conv."+getTypePostfix(Ty,false);
691 printSimpleInstruction(Tmp.c_str());
692 break;
693 // Do nothing
694 case Instruction::BitCast:
695 // FIXME: meaning that ld*/st* instruction do not change data format.
696 break;
697 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000698 errs() << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000699 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000700 }
701}
702
703
704void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
705 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000706 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000707 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000708 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000709 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000710 for (; I!=E; ++I){
711 Size = 0;
712 const Value* IndexValue = I.getOperand();
713 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
714 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
715 // Offset is the sum of all previous structure fields.
716 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000717 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000718 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000719 printSimpleInstruction("add");
720 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000721 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000722 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000723 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000724 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000725 }
726 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000727 if (!isZeroValue(IndexValue)) {
728 // Constant optimization.
729 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
730 if (C->getValue().isNegative()) {
731 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
732 printSimpleInstruction("sub");
733 continue;
734 } else
735 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000736 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000737 printPtrLoad(Size);
738 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000739 printSimpleInstruction("mul");
740 }
741 printSimpleInstruction("add");
742 }
743 }
744}
745
746
747std::string MSILWriter::getCallSignature(const FunctionType* Ty,
748 const Instruction* Inst,
749 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000750 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000751 if (Ty->isVarArg()) Tmp += "vararg ";
752 // Name and return type.
753 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
754 // Function argument type list.
755 unsigned NumParams = Ty->getNumParams();
756 for (unsigned I = 0; I!=NumParams; ++I) {
757 if (I!=0) Tmp += ",";
758 Tmp += getTypeName(Ty->getParamType(I));
759 }
760 // CLR needs to know the exact amount of parameters received by vararg
761 // function, because caller cleans the stack.
762 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000763 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000764 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
765 // Print variable argument types.
766 unsigned NumOperands = Inst->getNumOperands()-Org;
767 if (NumParams<NumOperands) {
768 if (NumParams!=0) Tmp += ", ";
769 Tmp += "... , ";
770 for (unsigned J = NumParams; J!=NumOperands; ++J) {
771 if (J!=NumParams) Tmp += ", ";
772 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
773 }
774 }
775 }
776 return Tmp+")";
777}
778
779
780void MSILWriter::printFunctionCall(const Value* FnVal,
781 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000782 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000783 std::string Name = "";
784 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
785 Name = getConvModopt(Call->getCallingConv());
786 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
787 Name = getConvModopt(Invoke->getCallingConv());
788 else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000789 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000790 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000791 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000792 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000793 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000794 Name += getValueName(F);
795 printSimpleInstruction("call",
796 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
797 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000798 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000799 const PointerType* PTy = cast<PointerType>(FnVal->getType());
800 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000801 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000802 printValueLoad(FnVal);
803 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
804 }
805}
806
807
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000808void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
809 std::string Name;
810 switch (Inst->getIntrinsicID()) {
811 case Intrinsic::vastart:
812 Name = getValueName(Inst->getOperand(1));
813 Name.insert(Name.length()-1,"$valist");
814 // Obtain the argument handle.
815 printSimpleInstruction("ldloca",Name.c_str());
816 printSimpleInstruction("arglist");
817 printSimpleInstruction("call",
818 "instance void [mscorlib]System.ArgIterator::.ctor"
819 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
820 // Save as pointer type "void*"
821 printValueLoad(Inst->getOperand(1));
822 printSimpleInstruction("ldloca",Name.c_str());
Owen Anderson1d0be152009-08-13 21:58:54 +0000823 printIndirectSave(PointerType::getUnqual(
824 IntegerType::get(Inst->getContext(), 8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000825 break;
826 case Intrinsic::vaend:
827 // Close argument list handle.
828 printIndirectLoad(Inst->getOperand(1));
829 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
830 break;
831 case Intrinsic::vacopy:
832 // Copy "ArgIterator" valuetype.
833 printIndirectLoad(Inst->getOperand(1));
834 printIndirectLoad(Inst->getOperand(2));
835 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
836 break;
837 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000838 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000839 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000840 }
841}
842
843
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000844void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000845 if (isa<IntrinsicInst>(Inst)) {
846 // Handle intrinsic function.
847 printIntrinsicCall(cast<IntrinsicInst>(Inst));
848 } else {
849 // Load arguments to stack and call function.
850 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
851 printValueLoad(Inst->getOperand(I));
852 printFunctionCall(Inst->getOperand(0),Inst);
853 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000854}
855
856
857void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
858 const Value* Right) {
859 switch (Predicate) {
860 case ICmpInst::ICMP_EQ:
861 printBinaryInstruction("ceq",Left,Right);
862 break;
863 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000864 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000865 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000866 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000867 printSimpleInstruction("not");
868 break;
869 case ICmpInst::ICMP_ULE:
870 case ICmpInst::ICMP_SLE:
871 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
872 printBinaryInstruction("ceq",Left,Right);
873 if (Predicate==ICmpInst::ICMP_ULE)
874 printBinaryInstruction("clt.un",Left,Right);
875 else
876 printBinaryInstruction("clt",Left,Right);
877 printSimpleInstruction("or");
878 break;
879 case ICmpInst::ICMP_UGE:
880 case ICmpInst::ICMP_SGE:
881 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
882 printBinaryInstruction("ceq",Left,Right);
883 if (Predicate==ICmpInst::ICMP_UGE)
884 printBinaryInstruction("cgt.un",Left,Right);
885 else
886 printBinaryInstruction("cgt",Left,Right);
887 printSimpleInstruction("or");
888 break;
889 case ICmpInst::ICMP_ULT:
890 printBinaryInstruction("clt.un",Left,Right);
891 break;
892 case ICmpInst::ICMP_SLT:
893 printBinaryInstruction("clt",Left,Right);
894 break;
895 case ICmpInst::ICMP_UGT:
896 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000897 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000898 case ICmpInst::ICMP_SGT:
899 printBinaryInstruction("cgt",Left,Right);
900 break;
901 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000902 errs() << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000903 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000904 }
905}
906
907
908void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
909 const Value* Right) {
910 // FIXME: Correct comparison
911 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
912 switch (Predicate) {
913 case FCmpInst::FCMP_UGT:
914 // X > Y || llvm_fcmp_uno(X, Y)
915 printBinaryInstruction("cgt",Left,Right);
916 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
917 printSimpleInstruction("or");
918 break;
919 case FCmpInst::FCMP_OGT:
920 // X > Y
921 printBinaryInstruction("cgt",Left,Right);
922 break;
923 case FCmpInst::FCMP_UGE:
924 // X >= Y || llvm_fcmp_uno(X, Y)
925 printBinaryInstruction("ceq",Left,Right);
926 printBinaryInstruction("cgt",Left,Right);
927 printSimpleInstruction("or");
928 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
929 printSimpleInstruction("or");
930 break;
931 case FCmpInst::FCMP_OGE:
932 // X >= Y
933 printBinaryInstruction("ceq",Left,Right);
934 printBinaryInstruction("cgt",Left,Right);
935 printSimpleInstruction("or");
936 break;
937 case FCmpInst::FCMP_ULT:
938 // X < Y || llvm_fcmp_uno(X, Y)
939 printBinaryInstruction("clt",Left,Right);
940 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
941 printSimpleInstruction("or");
942 break;
943 case FCmpInst::FCMP_OLT:
944 // X < Y
945 printBinaryInstruction("clt",Left,Right);
946 break;
947 case FCmpInst::FCMP_ULE:
948 // X <= Y || llvm_fcmp_uno(X, Y)
949 printBinaryInstruction("ceq",Left,Right);
950 printBinaryInstruction("clt",Left,Right);
951 printSimpleInstruction("or");
952 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
953 printSimpleInstruction("or");
954 break;
955 case FCmpInst::FCMP_OLE:
956 // X <= Y
957 printBinaryInstruction("ceq",Left,Right);
958 printBinaryInstruction("clt",Left,Right);
959 printSimpleInstruction("or");
960 break;
961 case FCmpInst::FCMP_UEQ:
962 // X == Y || llvm_fcmp_uno(X, Y)
963 printBinaryInstruction("ceq",Left,Right);
964 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
965 printSimpleInstruction("or");
966 break;
967 case FCmpInst::FCMP_OEQ:
968 // X == Y
969 printBinaryInstruction("ceq",Left,Right);
970 break;
971 case FCmpInst::FCMP_UNE:
972 // X != Y
973 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000974 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000975 printSimpleInstruction("not");
976 break;
977 case FCmpInst::FCMP_ONE:
978 // X != Y && llvm_fcmp_ord(X, Y)
979 printBinaryInstruction("ceq",Left,Right);
980 printSimpleInstruction("not");
981 break;
982 case FCmpInst::FCMP_ORD:
983 // return X == X && Y == Y
984 printBinaryInstruction("ceq",Left,Left);
985 printBinaryInstruction("ceq",Right,Right);
986 printSimpleInstruction("or");
987 break;
988 case FCmpInst::FCMP_UNO:
989 // X != X || Y != Y
990 printBinaryInstruction("ceq",Left,Left);
991 printSimpleInstruction("not");
992 printBinaryInstruction("ceq",Right,Right);
993 printSimpleInstruction("not");
994 printSimpleInstruction("or");
995 break;
996 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000997 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000998 }
999}
1000
1001
1002void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1003 std::string Label = "leave$normal_"+utostr(getUniqID());
1004 Out << ".try {\n";
1005 // Load arguments
1006 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1007 printValueLoad(Inst->getOperand(I));
1008 // Print call instruction
1009 printFunctionCall(Inst->getOperand(0),Inst);
1010 // Save function result and leave "try" block
1011 printValueSave(Inst);
1012 printSimpleInstruction("leave",Label.c_str());
1013 Out << "}\n";
1014 Out << "catch [mscorlib]System.Exception {\n";
1015 // Redirect to unwind block
1016 printSimpleInstruction("pop");
1017 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1018 Out << "}\n" << Label << ":\n";
1019 // Redirect to continue block
1020 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1021}
1022
1023
1024void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1025 // FIXME: Emulate with IL "switch" instruction
1026 // Emulate = if () else if () else if () else ...
1027 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1028 printValueLoad(Inst->getCondition());
1029 printValueLoad(Inst->getCaseValue(I));
1030 printSimpleInstruction("ceq");
1031 // Condition jump to successor block
1032 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1033 }
1034 // Jump to default block
1035 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1036}
1037
1038
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001039void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1040 printIndirectLoad(Inst->getOperand(0));
1041 printSimpleInstruction("call",
1042 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1043 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001044 std::string Name =
Owen Anderson1d0be152009-08-13 21:58:54 +00001045 "ldind."+getTypePostfix(PointerType::getUnqual(
1046 IntegerType::get(Inst->getContext(), 8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001047 printSimpleInstruction(Name.c_str());
1048}
1049
1050
1051void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001052 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001053 // Constant optimization.
1054 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1055 printPtrLoad(CInt->getZExtValue()*Size);
1056 } else {
1057 printPtrLoad(Size);
1058 printValueLoad(Inst->getOperand(0));
1059 printSimpleInstruction("mul");
1060 }
1061 printSimpleInstruction("localloc");
1062}
1063
1064
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001065void MSILWriter::printInstruction(const Instruction* Inst) {
1066 const Value *Left = 0, *Right = 0;
1067 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1068 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1069 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001070 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001071 switch (Inst->getOpcode()) {
1072 // Terminator
1073 case Instruction::Ret:
1074 if (Inst->getNumOperands()) {
1075 printValueLoad(Left);
1076 printSimpleInstruction("ret");
1077 } else
1078 printSimpleInstruction("ret");
1079 break;
1080 case Instruction::Br:
1081 printBranchInstruction(cast<BranchInst>(Inst));
1082 break;
1083 // Binary
1084 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001085 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001086 printBinaryInstruction("add",Left,Right);
1087 break;
1088 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001089 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001090 printBinaryInstruction("sub",Left,Right);
1091 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001092 case Instruction::Mul:
1093 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001094 printBinaryInstruction("mul",Left,Right);
1095 break;
1096 case Instruction::UDiv:
1097 printBinaryInstruction("div.un",Left,Right);
1098 break;
1099 case Instruction::SDiv:
1100 case Instruction::FDiv:
1101 printBinaryInstruction("div",Left,Right);
1102 break;
1103 case Instruction::URem:
1104 printBinaryInstruction("rem.un",Left,Right);
1105 break;
1106 case Instruction::SRem:
1107 case Instruction::FRem:
1108 printBinaryInstruction("rem",Left,Right);
1109 break;
1110 // Binary Condition
1111 case Instruction::ICmp:
1112 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1113 break;
1114 case Instruction::FCmp:
1115 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1116 break;
1117 // Bitwise Binary
1118 case Instruction::And:
1119 printBinaryInstruction("and",Left,Right);
1120 break;
1121 case Instruction::Or:
1122 printBinaryInstruction("or",Left,Right);
1123 break;
1124 case Instruction::Xor:
1125 printBinaryInstruction("xor",Left,Right);
1126 break;
1127 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001128 printValueLoad(Left);
1129 printValueLoad(Right);
1130 printSimpleInstruction("conv.i4");
1131 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001132 break;
1133 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001134 printValueLoad(Left);
1135 printValueLoad(Right);
1136 printSimpleInstruction("conv.i4");
1137 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001138 break;
1139 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001140 printValueLoad(Left);
1141 printValueLoad(Right);
1142 printSimpleInstruction("conv.i4");
1143 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001144 break;
1145 case Instruction::Select:
1146 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1147 break;
1148 case Instruction::Load:
1149 printIndirectLoad(Inst->getOperand(0));
1150 break;
1151 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001152 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001153 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001154 case Instruction::SExt:
1155 printCastInstruction(Inst->getOpcode(),Left,
1156 cast<CastInst>(Inst)->getDestTy(),
1157 cast<CastInst>(Inst)->getSrcTy());
1158 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001159 case Instruction::Trunc:
1160 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001161 case Instruction::FPTrunc:
1162 case Instruction::FPExt:
1163 case Instruction::UIToFP:
1164 case Instruction::SIToFP:
1165 case Instruction::FPToUI:
1166 case Instruction::FPToSI:
1167 case Instruction::PtrToInt:
1168 case Instruction::IntToPtr:
1169 case Instruction::BitCast:
1170 printCastInstruction(Inst->getOpcode(),Left,
1171 cast<CastInst>(Inst)->getDestTy());
1172 break;
1173 case Instruction::GetElementPtr:
1174 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1175 gep_type_end(Inst));
1176 break;
1177 case Instruction::Call:
1178 printCallInstruction(cast<CallInst>(Inst));
1179 break;
1180 case Instruction::Invoke:
1181 printInvokeInstruction(cast<InvokeInst>(Inst));
1182 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001183 case Instruction::Unwind:
1184 printSimpleInstruction("newobj",
1185 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001186 printSimpleInstruction("throw");
1187 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001188 case Instruction::Switch:
1189 printSwitchInstruction(cast<SwitchInst>(Inst));
1190 break;
1191 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001192 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001193 break;
1194 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001195 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001196 break;
1197 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001198 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001199 break;
1200 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001201 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1202 printSimpleInstruction("newobj",
1203 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001204 printSimpleInstruction("throw");
1205 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001206 case Instruction::VAArg:
1207 printVAArgInstruction(cast<VAArgInst>(Inst));
1208 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001209 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001210 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001211 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001212 }
1213}
1214
1215
1216void MSILWriter::printLoop(const Loop* L) {
1217 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1218 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1219 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1220 BasicBlock* BB = blocks[I];
1221 Loop* BBLoop = LInfo->getLoopFor(BB);
1222 if (BBLoop == L)
1223 printBasicBlock(BB);
1224 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1225 printLoop(BBLoop);
1226 }
1227 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1228}
1229
1230
1231void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1232 Out << getLabelName(BB) << ":\n";
1233 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1234 const Instruction* Inst = I;
1235 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001236 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001237 // Do not handle PHI instruction in current block
1238 if (Inst->getOpcode()==Instruction::PHI) continue;
1239 // Print instruction
1240 printInstruction(Inst);
1241 // Save result
Owen Anderson1d0be152009-08-13 21:58:54 +00001242 if (Inst->getType()!=Type::getVoidTy(BB->getContext())) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001243 // Do not save value after invoke, it done in "try" block
1244 if (Inst->getOpcode()==Instruction::Invoke) continue;
1245 printValueSave(Inst);
1246 }
1247 }
1248}
1249
1250
1251void MSILWriter::printLocalVariables(const Function& F) {
1252 std::string Name;
1253 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001254 std::set<const Value*> Printed;
1255 const Value* VaList = NULL;
1256 unsigned StackDepth = 8;
1257 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001258 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001259 if (I->getOpcode()==Instruction::Call ||
1260 I->getOpcode()==Instruction::Invoke) {
1261 // Test stack depth.
1262 if (StackDepth<I->getNumOperands())
1263 StackDepth = I->getNumOperands();
1264 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001265 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1266 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001267 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001268 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001269 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001270 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Owen Anderson1d0be152009-08-13 21:58:54 +00001271 } else if (I->getType()!=Type::getVoidTy(F.getContext())) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001272 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001273 Ty = I->getType();
1274 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001275 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1276 }
1277 // Test on 'va_list' variable
1278 bool isVaList = false;
1279 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1280 // "va_list" as "va_arg" instruction operand.
1281 isVaList = true;
1282 VaList = VaInst->getOperand(0);
1283 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1284 // "va_list" as intrinsic function operand.
1285 switch (Inst->getIntrinsicID()) {
1286 case Intrinsic::vastart:
1287 case Intrinsic::vaend:
1288 case Intrinsic::vacopy:
1289 isVaList = true;
1290 VaList = Inst->getOperand(1);
1291 break;
1292 default:
1293 isVaList = false;
1294 }
1295 }
1296 // Print "va_list" variable.
1297 if (isVaList && Printed.insert(VaList).second) {
1298 Name = getValueName(VaList);
1299 Name.insert(Name.length()-1,"$valist");
1300 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1301 << Name << ")\n";
1302 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001303 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001304 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001305}
1306
1307
1308void MSILWriter::printFunctionBody(const Function& F) {
1309 // Print body
1310 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1311 if (Loop *L = LInfo->getLoopFor(I)) {
1312 if (L->getHeader()==I && L->getParentLoop()==0)
1313 printLoop(L);
1314 } else {
1315 printBasicBlock(I);
1316 }
1317 }
1318}
1319
1320
1321void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1322 const Value *left = 0, *right = 0;
1323 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1324 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1325 // Print instruction
1326 switch (CE->getOpcode()) {
1327 case Instruction::Trunc:
1328 case Instruction::ZExt:
1329 case Instruction::SExt:
1330 case Instruction::FPTrunc:
1331 case Instruction::FPExt:
1332 case Instruction::UIToFP:
1333 case Instruction::SIToFP:
1334 case Instruction::FPToUI:
1335 case Instruction::FPToSI:
1336 case Instruction::PtrToInt:
1337 case Instruction::IntToPtr:
1338 case Instruction::BitCast:
1339 printCastInstruction(CE->getOpcode(),left,CE->getType());
1340 break;
1341 case Instruction::GetElementPtr:
1342 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1343 break;
1344 case Instruction::ICmp:
1345 printICmpInstruction(CE->getPredicate(),left,right);
1346 break;
1347 case Instruction::FCmp:
1348 printFCmpInstruction(CE->getPredicate(),left,right);
1349 break;
1350 case Instruction::Select:
1351 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1352 break;
1353 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001354 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001355 printBinaryInstruction("add",left,right);
1356 break;
1357 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001358 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001359 printBinaryInstruction("sub",left,right);
1360 break;
1361 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001362 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001363 printBinaryInstruction("mul",left,right);
1364 break;
1365 case Instruction::UDiv:
1366 printBinaryInstruction("div.un",left,right);
1367 break;
1368 case Instruction::SDiv:
1369 case Instruction::FDiv:
1370 printBinaryInstruction("div",left,right);
1371 break;
1372 case Instruction::URem:
1373 printBinaryInstruction("rem.un",left,right);
1374 break;
1375 case Instruction::SRem:
1376 case Instruction::FRem:
1377 printBinaryInstruction("rem",left,right);
1378 break;
1379 case Instruction::And:
1380 printBinaryInstruction("and",left,right);
1381 break;
1382 case Instruction::Or:
1383 printBinaryInstruction("or",left,right);
1384 break;
1385 case Instruction::Xor:
1386 printBinaryInstruction("xor",left,right);
1387 break;
1388 case Instruction::Shl:
1389 printBinaryInstruction("shl",left,right);
1390 break;
1391 case Instruction::LShr:
1392 printBinaryInstruction("shr.un",left,right);
1393 break;
1394 case Instruction::AShr:
1395 printBinaryInstruction("shr",left,right);
1396 break;
1397 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001398 errs() << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001399 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001400 }
1401}
1402
1403
1404void MSILWriter::printStaticInitializerList() {
1405 // List of global variables with uninitialized fields.
1406 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1407 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1408 ++VarI) {
1409 const std::vector<StaticInitializer>& InitList = VarI->second;
1410 if (InitList.empty()) continue;
1411 // For each uninitialized field.
1412 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1413 E = InitList.end(); I!=E; ++I) {
1414 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001415 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1416 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001417 // Load variable address
1418 printValueLoad(VarI->first);
1419 // Add offset
1420 if (I->offset!=0) {
1421 printPtrLoad(I->offset);
1422 printSimpleInstruction("add");
1423 }
1424 // Load value
1425 printConstantExpr(CE);
1426 // Save result at offset
1427 std::string postfix = getTypePostfix(CE->getType(),true);
1428 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1429 postfix = "stind."+postfix;
1430 printSimpleInstruction(postfix.c_str());
1431 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001432 errs() << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001433 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001434 }
1435 }
1436 }
1437}
1438
1439
1440void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001441 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001442 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001443 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001444 if (F.isVarArg()) Out << "vararg ";
1445 Out << getTypeName(F.getReturnType(),isSigned) <<
1446 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1447 // Arguments
1448 Out << "\t(";
1449 unsigned ArgIdx = 1;
1450 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1451 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001452 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001453 if (I!=F.arg_begin()) Out << ", ";
1454 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1455 }
1456 Out << ") cil managed\n";
1457 // Body
1458 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001459 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001460 printFunctionBody(F);
1461 Out << "}\n";
1462}
1463
1464
1465void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1466 std::string Name;
1467 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001468 for (std::set<const Type*>::const_iterator
1469 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1470 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001471 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1472 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001473 // Type with no need to declare.
1474 else continue;
1475 // Print not duplicated type
1476 if (Printed.insert(Ty).second) {
1477 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001478 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001479 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001480 }
1481 }
1482}
1483
1484
1485unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1486 unsigned int N = Ty->getPrimitiveSizeInBits();
1487 assert(N!=0 && "Invalid type in getBitWidth()");
1488 switch (N) {
1489 case 1:
1490 case 8:
1491 case 16:
1492 case 32:
1493 case 64:
1494 return N;
1495 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001496 errs() << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001497 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001498 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001499 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001500}
1501
1502
1503void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1504 uint64_t TySize = 0;
1505 const Type* Ty = C->getType();
1506 // Print zero initialized constant.
1507 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001508 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001509 Offset += TySize;
1510 Out << "int8 (0) [" << TySize << "]";
1511 return;
1512 }
1513 // Print constant initializer
1514 switch (Ty->getTypeID()) {
1515 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001516 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001517 const ConstantInt* Int = cast<ConstantInt>(C);
1518 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1519 break;
1520 }
1521 case Type::FloatTyID:
1522 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001523 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001524 const ConstantFP* FP = cast<ConstantFP>(C);
1525 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001526 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001527 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001528 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001529 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001530 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001531 break;
1532 }
1533 case Type::ArrayTyID:
1534 case Type::VectorTyID:
1535 case Type::StructTyID:
1536 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1537 if (I!=0) Out << ",\n";
1538 printStaticConstant(C->getOperand(I),Offset);
1539 }
1540 break;
1541 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001542 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001543 // Initialize with global variable address
1544 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1545 std::string name = getValueName(G);
1546 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1547 } else {
1548 // Dynamic initialization
1549 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1550 InitListPtr->push_back(StaticInitializer(C,Offset));
1551 // Null pointer initialization
1552 if (TySize==4) Out << "int32 (0)";
1553 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001554 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001555 }
1556 break;
1557 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001558 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001559 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001560 }
1561 // Increase offset.
1562 Offset += TySize;
1563}
1564
1565
1566void MSILWriter::printStaticInitializer(const Constant* C,
1567 const std::string& Name) {
1568 switch (C->getType()->getTypeID()) {
1569 case Type::IntegerTyID:
1570 case Type::FloatTyID:
1571 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001572 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001573 break;
1574 case Type::ArrayTyID:
1575 case Type::VectorTyID:
1576 case Type::StructTyID:
1577 case Type::PointerTyID:
1578 Out << getTypeName(C->getType());
1579 break;
1580 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001581 errs() << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001582 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001583 }
1584 // Print initializer
1585 std::string label = Name;
1586 label.insert(label.length()-1,"$data");
1587 Out << Name << " at " << label << '\n';
1588 Out << ".data " << label << " = {\n";
1589 uint64_t offset = 0;
1590 printStaticConstant(C,offset);
1591 Out << "\n}\n\n";
1592}
1593
1594
1595void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1596 const Constant* C = G->getInitializer();
1597 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1598 InitListPtr = 0;
1599 else
1600 InitListPtr = &StaticInitList[G];
1601 printStaticInitializer(C,getValueName(G));
1602}
1603
1604
1605void MSILWriter::printGlobalVariables() {
1606 if (ModulePtr->global_empty()) return;
1607 Module::global_iterator I,E;
1608 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1609 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001610 Out << ".field static " << (I->isDeclaration() ? "public " :
1611 "private ");
1612 if (I->isDeclaration()) {
1613 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1614 } else
1615 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001616 }
1617}
1618
1619
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001620const char* MSILWriter::getLibraryName(const Function* F) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001621 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001622}
1623
1624
1625const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001626 return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001627}
1628
1629
Daniel Dunbarbda96532009-07-21 08:57:31 +00001630const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1631 bool isFunction,
1632 unsigned CallingConv) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001633 // TODO: Read *.def file with function and libraries definitions.
1634 return "MSVCRT.DLL";
1635}
1636
1637
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001638void MSILWriter::printExternals() {
1639 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001640 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001641 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1642 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001643 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001644 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001645 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001646 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001647 std::string Sig =
1648 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1649 Out << ".method static hidebysig pinvokeimpl(\""
1650 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001651 }
1652 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001653 // External variables and static initialization.
1654 Out <<
1655 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1656 " native int LoadLibrary(string) preservesig {}\n"
1657 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1658 " native int GetProcAddress(native int, string) preservesig {}\n";
1659 Out <<
1660 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1661 " managed cil\n{\n"
1662 "\tldarg\tlib\n"
1663 "\tcall\tnative int LoadLibrary(string)\n"
1664 "\tldarg\tsym\n"
1665 "\tcall\tnative int GetProcAddress(native int,string)\n"
1666 "\tdup\n"
1667 "\tbrtrue\tL_01\n"
1668 "\tldstr\t\"Can no import variable\"\n"
1669 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1670 "\tthrow\n"
1671 "L_01:\n"
1672 "\tret\n"
1673 "}\n\n"
1674 ".method static private void $MSIL_Init() managed cil\n{\n";
1675 printStaticInitializerList();
1676 // Foreach global variable.
1677 for (Module::global_iterator I = ModulePtr->global_begin(),
1678 E = ModulePtr->global_end(); I!=E; ++I) {
1679 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1680 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1681 std::string Label = "not_null$_"+utostr(getUniqID());
1682 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1683 printSimpleInstruction("ldsflda",Tmp.c_str());
1684 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001685 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001686 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1687 printIndirectSave(I->getType());
1688 }
1689 printSimpleInstruction("ret");
1690 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001691}
1692
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001693
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001694//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001695// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001696//===----------------------------------------------------------------------===//
1697
David Greene71847812009-07-14 20:18:05 +00001698bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1699 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001700 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001701 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001702{
1703 if (FileType != TargetMachine::AssemblyFile) return true;
1704 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001705 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001706 PM.add(createLowerAllocationsPass(true));
1707 // FIXME: Handle switch trougth native IL instruction "switch"
1708 PM.add(createLowerSwitchPass());
1709 PM.add(createCFGSimplificationPass());
1710 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1711 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001712 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001713 return false;
1714}