blob: 6e0f3b6d42cea75a0c023685c380a18b3b8e4aae [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 {
34 const TargetData DataLayout; // Calculates type size & alignment
35
Daniel Dunbar51b198a2009-07-15 20:24:03 +000036 MSILTarget(const Target &T, const Module &M, const std::string &FS)
37 : TargetMachine(T), DataLayout(&M) {}
Anton Korobeynikov099883f2007-03-21 21:38:25 +000038
39 virtual bool WantsWholeFile() const { return true; }
David Greene71847812009-07-14 20:18:05 +000040 virtual bool addPassesToEmitWholeFile(PassManager &PM,
41 formatted_raw_ostream &Out,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000042 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +000043 CodeGenOpt::Level OptLevel);
Anton Korobeynikov099883f2007-03-21 21:38:25 +000044
45 // This class always works, but shouldn't be the default in most cases.
46 static unsigned getModuleMatchQuality(const Module &M) { return 1; }
47
48 virtual const TargetData *getTargetData() const { return &DataLayout; }
49 };
50}
51
Daniel Dunbar0c795d62009-07-25 06:49:55 +000052extern "C" void LLVMInitializeMSILTarget() {
53 // Register the target.
54 RegisterTargetMachine<MSILTarget> X(TheMSILTarget);
55}
Douglas Gregor1555a232009-06-16 20:12:29 +000056
Anton Korobeynikov099883f2007-03-21 21:38:25 +000057bool MSILModule::runOnModule(Module &M) {
58 ModulePtr = &M;
59 TD = &getAnalysis<TargetData>();
60 bool Changed = false;
61 // Find named types.
62 TypeSymbolTable& Table = M.getTypeSymbolTable();
63 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
64 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
65 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
66 Table.remove(I++);
67 else {
68 std::set<const Type *>::iterator T = Types.find(I->second);
69 if (T==Types.end())
70 Table.remove(I++);
71 else {
72 Types.erase(T);
73 ++I;
74 }
75 }
76 }
77 // Find unnamed types.
78 unsigned RenameCounter = 0;
79 for (std::set<const Type *>::const_iterator I = Types.begin(),
80 E = Types.end(); I!=E; ++I)
81 if (const StructType *STy = dyn_cast<StructType>(*I)) {
82 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
83 ++RenameCounter;
84 Changed = true;
85 }
86 // Pointer for FunctionPass.
87 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
88 return Changed;
89}
90
Devang Patel19974732007-05-03 01:11:54 +000091char MSILModule::ID = 0;
92char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000093
94bool MSILWriter::runOnFunction(Function &F) {
95 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000096
97 // Do not codegen any 'available_externally' functions at all, they have
98 // definitions outside the translation unit.
99 if (F.hasAvailableExternallyLinkage())
100 return false;
101
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000102 LInfo = &getAnalysis<LoopInfo>();
103 printFunction(F);
104 return false;
105}
106
107
108bool MSILWriter::doInitialization(Module &M) {
109 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000110 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000111 Out << ".assembly extern mscorlib {}\n";
112 Out << ".assembly MSIL {}\n\n";
113 Out << "// External\n";
114 printExternals();
115 Out << "// Declarations\n";
116 printDeclarations(M.getTypeSymbolTable());
117 Out << "// Definitions\n";
118 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000119 Out << "// Startup code\n";
120 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000121 return false;
122}
123
124
125bool MSILWriter::doFinalization(Module &M) {
126 delete Mang;
127 return false;
128}
129
130
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000131void MSILWriter::printModuleStartup() {
132 Out <<
133 ".method static public int32 $MSIL_Startup() {\n"
134 "\t.entrypoint\n"
135 "\t.locals (native int i)\n"
136 "\t.locals (native int argc)\n"
137 "\t.locals (native int ptr)\n"
138 "\t.locals (void* argv)\n"
139 "\t.locals (string[] args)\n"
140 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
141 "\tdup\n"
142 "\tstloc\targs\n"
143 "\tldlen\n"
144 "\tconv.i4\n"
145 "\tdup\n"
146 "\tstloc\targc\n";
147 printPtrLoad(TD->getPointerSize());
148 Out <<
149 "\tmul\n"
150 "\tlocalloc\n"
151 "\tstloc\targv\n"
152 "\tldc.i4.0\n"
153 "\tstloc\ti\n"
154 "L_01:\n"
155 "\tldloc\ti\n"
156 "\tldloc\targc\n"
157 "\tceq\n"
158 "\tbrtrue\tL_02\n"
159 "\tldloc\targs\n"
160 "\tldloc\ti\n"
161 "\tldelem.ref\n"
162 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
163 "StringToHGlobalAnsi(string)\n"
164 "\tstloc\tptr\n"
165 "\tldloc\targv\n"
166 "\tldloc\ti\n";
167 printPtrLoad(TD->getPointerSize());
168 Out <<
169 "\tmul\n"
170 "\tadd\n"
171 "\tldloc\tptr\n"
172 "\tstind.i\n"
173 "\tldloc\ti\n"
174 "\tldc.i4.1\n"
175 "\tadd\n"
176 "\tstloc\ti\n"
177 "\tbr\tL_01\n"
178 "L_02:\n"
179 "\tcall void $MSIL_Init()\n";
180
181 // Call user 'main' function.
182 const Function* F = ModulePtr->getFunction("main");
183 if (!F || F->isDeclaration()) {
184 Out << "\tldc.i4.0\n\tret\n}\n";
185 return;
186 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000187 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000188 std::string Args("");
189 Function::const_arg_iterator Arg1,Arg2;
190
191 switch (F->arg_size()) {
192 case 0:
193 BadSig = false;
194 break;
195 case 1:
196 Arg1 = F->arg_begin();
197 if (Arg1->getType()->isInteger()) {
198 Out << "\tldloc\targc\n";
199 Args = getTypeName(Arg1->getType());
200 BadSig = false;
201 }
202 break;
203 case 2:
204 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
205 if (Arg1->getType()->isInteger() &&
206 Arg2->getType()->getTypeID() == Type::PointerTyID) {
207 Out << "\tldloc\targc\n\tldloc\targv\n";
208 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
209 BadSig = false;
210 }
211 break;
212 default:
213 BadSig = true;
214 }
215
216 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000217 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000218 Out << "\tldc.i4.0\n";
219 } else {
220 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
221 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
222 if (RetVoid)
223 Out << "\tldc.i4.0\n";
224 else
225 Out << "\tconv.i4\n";
226 }
227 Out << "\tret\n}\n";
228}
229
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000230bool MSILWriter::isZeroValue(const Value* V) {
231 if (const Constant *C = dyn_cast<Constant>(V))
232 return C->isNullValue();
233 return false;
234}
235
236
237std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000238 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000239 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000240 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000241 else {
242 unsigned &No = AnonValueNumbers[V];
243 if (No == 0) No = ++NextAnonValueNumber;
244 Name = "tmp" + utostr(No);
245 }
246
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000247 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000248 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000249}
250
251
252std::string MSILWriter::getLabelName(const std::string& Name) {
253 if (Name.find('.')!=std::string::npos) {
254 std::string Tmp(Name);
255 // Replace unaccepable characters in the label name.
256 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
257 if (*I=='.') *I = '@';
258 return Tmp;
259 }
260 return Name;
261}
262
263
264std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000265 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000266 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000267 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000268 else {
269 unsigned &No = AnonValueNumbers[V];
270 if (No == 0) No = ++NextAnonValueNumber;
271 Name = "tmp" + utostr(No);
272 }
273
274 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000275}
276
277
278std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
279 switch (CallingConvID) {
280 case CallingConv::C:
281 case CallingConv::Cold:
282 case CallingConv::Fast:
283 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
284 case CallingConv::X86_FastCall:
285 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
286 case CallingConv::X86_StdCall:
287 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
288 default:
289 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000290 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000291 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000292 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000293}
294
295
296std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
297 std::string Tmp = "";
298 const Type* ElemTy = Ty;
299 assert(Ty->getTypeID()==TyID && "Invalid type passed");
300 // Walk trought array element types.
301 for (;;) {
302 // Multidimensional array.
303 if (ElemTy->getTypeID()==TyID) {
304 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
305 Tmp += utostr(ATy->getNumElements());
306 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
307 Tmp += utostr(VTy->getNumElements());
308 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
309 }
310 // Base element type found.
311 if (ElemTy->getTypeID()!=TyID) break;
312 Tmp += ",";
313 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000314 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000315}
316
317
318std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
319 unsigned NumBits = 0;
320 switch (Ty->getTypeID()) {
321 case Type::VoidTyID:
322 return "void ";
323 case Type::IntegerTyID:
324 NumBits = getBitWidth(Ty);
325 if(NumBits==1)
326 return "bool ";
327 if (!isSigned)
328 return "unsigned int"+utostr(NumBits)+" ";
329 return "int"+utostr(NumBits)+" ";
330 case Type::FloatTyID:
331 return "float32 ";
332 case Type::DoubleTyID:
333 return "float64 ";
334 default:
335 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000336 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000337 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000338 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000339}
340
341
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000342std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
343 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000344 if (Ty->isPrimitiveType() || Ty->isInteger())
345 return getPrimitiveTypeName(Ty,isSigned);
346 // FIXME: "OpaqueType" support
347 switch (Ty->getTypeID()) {
348 case Type::PointerTyID:
349 return "void* ";
350 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000351 if (isNested)
352 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000353 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
354 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000355 if (isNested)
356 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000357 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
358 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000359 if (isNested)
360 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000361 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
362 default:
363 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000364 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000365 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000366 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000367}
368
369
370MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
371 // Function argument
372 if (isa<Argument>(V))
373 return ArgumentVT;
374 // Function
375 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000376 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000377 // Variable
378 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000379 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000380 // Constant
381 else if (isa<Constant>(V))
382 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
383 // Local variable
384 return LocalVT;
385}
386
387
388std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
389 bool isSigned) {
390 unsigned NumBits = 0;
391 switch (Ty->getTypeID()) {
392 // Integer constant, expanding for stack operations.
393 case Type::IntegerTyID:
394 NumBits = getBitWidth(Ty);
395 // Expand integer value to "int32" or "int64".
396 if (Expand) return (NumBits<=32 ? "i4" : "i8");
397 if (NumBits==1) return "i1";
398 return (isSigned ? "i" : "u")+utostr(NumBits/8);
399 // Float constant.
400 case Type::FloatTyID:
401 return "r4";
402 case Type::DoubleTyID:
403 return "r8";
404 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000405 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000406 default:
407 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000408 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000409 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000410 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000411}
412
413
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000414void MSILWriter::printConvToPtr() {
415 switch (ModulePtr->getPointerSize()) {
416 case Module::Pointer32:
417 printSimpleInstruction("conv.u4");
418 break;
419 case Module::Pointer64:
420 printSimpleInstruction("conv.u8");
421 break;
422 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000423 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000424 }
425}
426
427
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000428void MSILWriter::printPtrLoad(uint64_t N) {
429 switch (ModulePtr->getPointerSize()) {
430 case Module::Pointer32:
431 printSimpleInstruction("ldc.i4",utostr(N).c_str());
432 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000433 if (!isUInt32(N)) {
434 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000435 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000436 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000437 break;
438 case Module::Pointer64:
439 printSimpleInstruction("ldc.i8",utostr(N).c_str());
440 break;
441 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000442 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000443 }
444}
445
446
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000447void MSILWriter::printValuePtrLoad(const Value* V) {
448 printValueLoad(V);
449 printConvToPtr();
450}
451
452
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000453void MSILWriter::printConstLoad(const Constant* C) {
454 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
455 // Integer constant
456 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
457 if (CInt->isMinValue(true))
458 Out << CInt->getSExtValue();
459 else
460 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000461 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000462 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000463 uint64_t X;
464 unsigned Size;
465 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000466 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000467 Size = 4;
468 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000469 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000470 Size = 8;
471 }
472 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
473 } else if (isa<UndefValue>(C)) {
474 // Undefined constant value = NULL.
475 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000476 } else {
477 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000478 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000479 }
480 Out << '\n';
481}
482
483
484void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000485 MSILWriter::ValueType Location = getValueLocation(V);
486 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000487 // Global variable or function address.
488 case GlobalVT:
489 case InternalVT:
490 if (const Function* F = dyn_cast<Function>(V)) {
491 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
492 printSimpleInstruction("ldftn",
493 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
494 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000495 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000496 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000497 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
498 Tmp = "void* "+getValueName(V);
499 printSimpleInstruction("ldsfld",Tmp.c_str());
500 } else {
501 Tmp = getTypeName(ElemTy)+getValueName(V);
502 printSimpleInstruction("ldsflda",Tmp.c_str());
503 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000504 }
505 break;
506 // Function argument.
507 case ArgumentVT:
508 printSimpleInstruction("ldarg",getValueName(V).c_str());
509 break;
510 // Local function variable.
511 case LocalVT:
512 printSimpleInstruction("ldloc",getValueName(V).c_str());
513 break;
514 // Constant value.
515 case ConstVT:
516 if (isa<ConstantPointerNull>(V))
517 printPtrLoad(0);
518 else
519 printConstLoad(cast<Constant>(V));
520 break;
521 // Constant expression.
522 case ConstExprVT:
523 printConstantExpr(cast<ConstantExpr>(V));
524 break;
525 default:
526 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000527 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000528 }
529}
530
531
532void MSILWriter::printValueSave(const Value* V) {
533 switch (getValueLocation(V)) {
534 case ArgumentVT:
535 printSimpleInstruction("starg",getValueName(V).c_str());
536 break;
537 case LocalVT:
538 printSimpleInstruction("stloc",getValueName(V).c_str());
539 break;
540 default:
541 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000542 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000543 }
544}
545
546
547void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
548 const Value* Right) {
549 printValueLoad(Left);
550 printValueLoad(Right);
551 Out << '\t' << Name << '\n';
552}
553
554
555void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
556 if(Operand)
557 Out << '\t' << Inst << '\t' << Operand << '\n';
558 else
559 Out << '\t' << Inst << '\n';
560}
561
562
563void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
564 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
565 isa<PHINode>(I); ++I) {
566 const PHINode* Phi = cast<PHINode>(I);
567 const Value* Val = Phi->getIncomingValueForBlock(Src);
568 if (isa<UndefValue>(Val)) continue;
569 printValueLoad(Val);
570 printValueSave(Phi);
571 }
572}
573
574
575void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
576 const BasicBlock* TrueBB,
577 const BasicBlock* FalseBB) {
578 if (TrueBB==FalseBB) {
579 // "TrueBB" and "FalseBB" destination equals
580 printPHICopy(CurrBB,TrueBB);
581 printSimpleInstruction("pop");
582 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
583 } else if (FalseBB==NULL) {
584 // If "FalseBB" not used the jump have condition
585 printPHICopy(CurrBB,TrueBB);
586 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
587 } else if (TrueBB==NULL) {
588 // If "TrueBB" not used the jump is unconditional
589 printPHICopy(CurrBB,FalseBB);
590 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
591 } else {
592 // Copy PHI instructions for each block
593 std::string TmpLabel;
594 // Print PHI instructions for "TrueBB"
595 if (isa<PHINode>(TrueBB->begin())) {
596 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
597 printSimpleInstruction("brtrue",TmpLabel.c_str());
598 } else {
599 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
600 }
601 // Print PHI instructions for "FalseBB"
602 if (isa<PHINode>(FalseBB->begin())) {
603 printPHICopy(CurrBB,FalseBB);
604 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
605 } else {
606 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
607 }
608 if (isa<PHINode>(TrueBB->begin())) {
609 // Handle "TrueBB" PHI Copy
610 Out << TmpLabel << ":\n";
611 printPHICopy(CurrBB,TrueBB);
612 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
613 }
614 }
615}
616
617
618void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
619 if (Inst->isUnconditional()) {
620 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
621 } else {
622 printValueLoad(Inst->getCondition());
623 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
624 Inst->getSuccessor(1));
625 }
626}
627
628
629void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
630 const Value* VFalse) {
631 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
632 printValueLoad(VTrue);
633 printValueLoad(Cond);
634 printSimpleInstruction("brtrue",TmpLabel.c_str());
635 printSimpleInstruction("pop");
636 printValueLoad(VFalse);
637 Out << TmpLabel << ":\n";
638}
639
640
641void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000642 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000643 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000644 if (const PointerType* P = dyn_cast<PointerType>(Ty))
645 Ty = P->getElementType();
646 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000647 printSimpleInstruction(Tmp.c_str());
648}
649
650
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000651void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000652 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000653 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000654 printIndirectSave(Val->getType());
655}
656
657
658void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000659 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000660 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000661 if (*postfix.begin()=='u') *postfix.begin() = 'i';
662 postfix = "stind."+postfix;
663 printSimpleInstruction(postfix.c_str());
664}
665
666
667void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000668 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000669 std::string Tmp("");
670 printValueLoad(V);
671 switch (Op) {
672 // Signed
673 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000674 // If sign extending int, convert first from unsigned to signed
675 // with the same bit size - because otherwise we will loose the sign.
676 if (SrcTy) {
677 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
678 printSimpleInstruction(Tmp.c_str());
679 }
Bill Wendling5f544502009-07-14 18:30:04 +0000680 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000681 case Instruction::SIToFP:
682 case Instruction::FPToSI:
683 Tmp = "conv."+getTypePostfix(Ty,false,true);
684 printSimpleInstruction(Tmp.c_str());
685 break;
686 // Unsigned
687 case Instruction::FPTrunc:
688 case Instruction::FPExt:
689 case Instruction::UIToFP:
690 case Instruction::Trunc:
691 case Instruction::ZExt:
692 case Instruction::FPToUI:
693 case Instruction::PtrToInt:
694 case Instruction::IntToPtr:
695 Tmp = "conv."+getTypePostfix(Ty,false);
696 printSimpleInstruction(Tmp.c_str());
697 break;
698 // Do nothing
699 case Instruction::BitCast:
700 // FIXME: meaning that ld*/st* instruction do not change data format.
701 break;
702 default:
703 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000704 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000705 }
706}
707
708
709void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
710 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000711 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000712 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000713 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000714 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000715 for (; I!=E; ++I){
716 Size = 0;
717 const Value* IndexValue = I.getOperand();
718 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
719 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
720 // Offset is the sum of all previous structure fields.
721 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000722 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000723 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000724 printSimpleInstruction("add");
725 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000726 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000727 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000728 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000729 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000730 }
731 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000732 if (!isZeroValue(IndexValue)) {
733 // Constant optimization.
734 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
735 if (C->getValue().isNegative()) {
736 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
737 printSimpleInstruction("sub");
738 continue;
739 } else
740 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000741 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000742 printPtrLoad(Size);
743 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000744 printSimpleInstruction("mul");
745 }
746 printSimpleInstruction("add");
747 }
748 }
749}
750
751
752std::string MSILWriter::getCallSignature(const FunctionType* Ty,
753 const Instruction* Inst,
754 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000755 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000756 if (Ty->isVarArg()) Tmp += "vararg ";
757 // Name and return type.
758 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
759 // Function argument type list.
760 unsigned NumParams = Ty->getNumParams();
761 for (unsigned I = 0; I!=NumParams; ++I) {
762 if (I!=0) Tmp += ",";
763 Tmp += getTypeName(Ty->getParamType(I));
764 }
765 // CLR needs to know the exact amount of parameters received by vararg
766 // function, because caller cleans the stack.
767 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000768 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000769 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
770 // Print variable argument types.
771 unsigned NumOperands = Inst->getNumOperands()-Org;
772 if (NumParams<NumOperands) {
773 if (NumParams!=0) Tmp += ", ";
774 Tmp += "... , ";
775 for (unsigned J = NumParams; J!=NumOperands; ++J) {
776 if (J!=NumParams) Tmp += ", ";
777 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
778 }
779 }
780 }
781 return Tmp+")";
782}
783
784
785void MSILWriter::printFunctionCall(const Value* FnVal,
786 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000787 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000788 std::string Name = "";
789 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
790 Name = getConvModopt(Call->getCallingConv());
791 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
792 Name = getConvModopt(Invoke->getCallingConv());
793 else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000794 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000795 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000796 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000797 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000798 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000799 Name += getValueName(F);
800 printSimpleInstruction("call",
801 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
802 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000803 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000804 const PointerType* PTy = cast<PointerType>(FnVal->getType());
805 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000806 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000807 printValueLoad(FnVal);
808 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
809 }
810}
811
812
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000813void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
814 std::string Name;
815 switch (Inst->getIntrinsicID()) {
816 case Intrinsic::vastart:
817 Name = getValueName(Inst->getOperand(1));
818 Name.insert(Name.length()-1,"$valist");
819 // Obtain the argument handle.
820 printSimpleInstruction("ldloca",Name.c_str());
821 printSimpleInstruction("arglist");
822 printSimpleInstruction("call",
823 "instance void [mscorlib]System.ArgIterator::.ctor"
824 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
825 // Save as pointer type "void*"
826 printValueLoad(Inst->getOperand(1));
827 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000828 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000829 break;
830 case Intrinsic::vaend:
831 // Close argument list handle.
832 printIndirectLoad(Inst->getOperand(1));
833 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
834 break;
835 case Intrinsic::vacopy:
836 // Copy "ArgIterator" valuetype.
837 printIndirectLoad(Inst->getOperand(1));
838 printIndirectLoad(Inst->getOperand(2));
839 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
840 break;
841 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000842 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000843 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000844 }
845}
846
847
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000848void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000849 if (isa<IntrinsicInst>(Inst)) {
850 // Handle intrinsic function.
851 printIntrinsicCall(cast<IntrinsicInst>(Inst));
852 } else {
853 // Load arguments to stack and call function.
854 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
855 printValueLoad(Inst->getOperand(I));
856 printFunctionCall(Inst->getOperand(0),Inst);
857 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000858}
859
860
861void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
862 const Value* Right) {
863 switch (Predicate) {
864 case ICmpInst::ICMP_EQ:
865 printBinaryInstruction("ceq",Left,Right);
866 break;
867 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000868 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000869 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000870 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000871 printSimpleInstruction("not");
872 break;
873 case ICmpInst::ICMP_ULE:
874 case ICmpInst::ICMP_SLE:
875 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
876 printBinaryInstruction("ceq",Left,Right);
877 if (Predicate==ICmpInst::ICMP_ULE)
878 printBinaryInstruction("clt.un",Left,Right);
879 else
880 printBinaryInstruction("clt",Left,Right);
881 printSimpleInstruction("or");
882 break;
883 case ICmpInst::ICMP_UGE:
884 case ICmpInst::ICMP_SGE:
885 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
886 printBinaryInstruction("ceq",Left,Right);
887 if (Predicate==ICmpInst::ICMP_UGE)
888 printBinaryInstruction("cgt.un",Left,Right);
889 else
890 printBinaryInstruction("cgt",Left,Right);
891 printSimpleInstruction("or");
892 break;
893 case ICmpInst::ICMP_ULT:
894 printBinaryInstruction("clt.un",Left,Right);
895 break;
896 case ICmpInst::ICMP_SLT:
897 printBinaryInstruction("clt",Left,Right);
898 break;
899 case ICmpInst::ICMP_UGT:
900 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000901 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000902 case ICmpInst::ICMP_SGT:
903 printBinaryInstruction("cgt",Left,Right);
904 break;
905 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000906 errs() << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000907 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000908 }
909}
910
911
912void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
913 const Value* Right) {
914 // FIXME: Correct comparison
915 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
916 switch (Predicate) {
917 case FCmpInst::FCMP_UGT:
918 // X > Y || llvm_fcmp_uno(X, Y)
919 printBinaryInstruction("cgt",Left,Right);
920 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
921 printSimpleInstruction("or");
922 break;
923 case FCmpInst::FCMP_OGT:
924 // X > Y
925 printBinaryInstruction("cgt",Left,Right);
926 break;
927 case FCmpInst::FCMP_UGE:
928 // X >= Y || llvm_fcmp_uno(X, Y)
929 printBinaryInstruction("ceq",Left,Right);
930 printBinaryInstruction("cgt",Left,Right);
931 printSimpleInstruction("or");
932 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
933 printSimpleInstruction("or");
934 break;
935 case FCmpInst::FCMP_OGE:
936 // X >= Y
937 printBinaryInstruction("ceq",Left,Right);
938 printBinaryInstruction("cgt",Left,Right);
939 printSimpleInstruction("or");
940 break;
941 case FCmpInst::FCMP_ULT:
942 // X < Y || llvm_fcmp_uno(X, Y)
943 printBinaryInstruction("clt",Left,Right);
944 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
945 printSimpleInstruction("or");
946 break;
947 case FCmpInst::FCMP_OLT:
948 // X < Y
949 printBinaryInstruction("clt",Left,Right);
950 break;
951 case FCmpInst::FCMP_ULE:
952 // X <= Y || llvm_fcmp_uno(X, Y)
953 printBinaryInstruction("ceq",Left,Right);
954 printBinaryInstruction("clt",Left,Right);
955 printSimpleInstruction("or");
956 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
957 printSimpleInstruction("or");
958 break;
959 case FCmpInst::FCMP_OLE:
960 // X <= Y
961 printBinaryInstruction("ceq",Left,Right);
962 printBinaryInstruction("clt",Left,Right);
963 printSimpleInstruction("or");
964 break;
965 case FCmpInst::FCMP_UEQ:
966 // X == Y || llvm_fcmp_uno(X, Y)
967 printBinaryInstruction("ceq",Left,Right);
968 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
969 printSimpleInstruction("or");
970 break;
971 case FCmpInst::FCMP_OEQ:
972 // X == Y
973 printBinaryInstruction("ceq",Left,Right);
974 break;
975 case FCmpInst::FCMP_UNE:
976 // X != Y
977 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000978 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000979 printSimpleInstruction("not");
980 break;
981 case FCmpInst::FCMP_ONE:
982 // X != Y && llvm_fcmp_ord(X, Y)
983 printBinaryInstruction("ceq",Left,Right);
984 printSimpleInstruction("not");
985 break;
986 case FCmpInst::FCMP_ORD:
987 // return X == X && Y == Y
988 printBinaryInstruction("ceq",Left,Left);
989 printBinaryInstruction("ceq",Right,Right);
990 printSimpleInstruction("or");
991 break;
992 case FCmpInst::FCMP_UNO:
993 // X != X || Y != Y
994 printBinaryInstruction("ceq",Left,Left);
995 printSimpleInstruction("not");
996 printBinaryInstruction("ceq",Right,Right);
997 printSimpleInstruction("not");
998 printSimpleInstruction("or");
999 break;
1000 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001001 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001002 }
1003}
1004
1005
1006void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1007 std::string Label = "leave$normal_"+utostr(getUniqID());
1008 Out << ".try {\n";
1009 // Load arguments
1010 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1011 printValueLoad(Inst->getOperand(I));
1012 // Print call instruction
1013 printFunctionCall(Inst->getOperand(0),Inst);
1014 // Save function result and leave "try" block
1015 printValueSave(Inst);
1016 printSimpleInstruction("leave",Label.c_str());
1017 Out << "}\n";
1018 Out << "catch [mscorlib]System.Exception {\n";
1019 // Redirect to unwind block
1020 printSimpleInstruction("pop");
1021 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1022 Out << "}\n" << Label << ":\n";
1023 // Redirect to continue block
1024 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1025}
1026
1027
1028void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1029 // FIXME: Emulate with IL "switch" instruction
1030 // Emulate = if () else if () else if () else ...
1031 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1032 printValueLoad(Inst->getCondition());
1033 printValueLoad(Inst->getCaseValue(I));
1034 printSimpleInstruction("ceq");
1035 // Condition jump to successor block
1036 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1037 }
1038 // Jump to default block
1039 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1040}
1041
1042
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001043void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1044 printIndirectLoad(Inst->getOperand(0));
1045 printSimpleInstruction("call",
1046 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1047 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001048 std::string Name =
1049 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(8)),false);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001050 printSimpleInstruction(Name.c_str());
1051}
1052
1053
1054void MSILWriter::printAllocaInstruction(const AllocaInst* Inst) {
Duncan Sands777d2302009-05-09 07:06:46 +00001055 uint64_t Size = TD->getTypeAllocSize(Inst->getAllocatedType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001056 // Constant optimization.
1057 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
1058 printPtrLoad(CInt->getZExtValue()*Size);
1059 } else {
1060 printPtrLoad(Size);
1061 printValueLoad(Inst->getOperand(0));
1062 printSimpleInstruction("mul");
1063 }
1064 printSimpleInstruction("localloc");
1065}
1066
1067
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001068void MSILWriter::printInstruction(const Instruction* Inst) {
1069 const Value *Left = 0, *Right = 0;
1070 if (Inst->getNumOperands()>=1) Left = Inst->getOperand(0);
1071 if (Inst->getNumOperands()>=2) Right = Inst->getOperand(1);
1072 // Print instruction
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001073 // FIXME: "ShuffleVector","ExtractElement","InsertElement" support.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001074 switch (Inst->getOpcode()) {
1075 // Terminator
1076 case Instruction::Ret:
1077 if (Inst->getNumOperands()) {
1078 printValueLoad(Left);
1079 printSimpleInstruction("ret");
1080 } else
1081 printSimpleInstruction("ret");
1082 break;
1083 case Instruction::Br:
1084 printBranchInstruction(cast<BranchInst>(Inst));
1085 break;
1086 // Binary
1087 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001088 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001089 printBinaryInstruction("add",Left,Right);
1090 break;
1091 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001092 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001093 printBinaryInstruction("sub",Left,Right);
1094 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001095 case Instruction::Mul:
1096 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001097 printBinaryInstruction("mul",Left,Right);
1098 break;
1099 case Instruction::UDiv:
1100 printBinaryInstruction("div.un",Left,Right);
1101 break;
1102 case Instruction::SDiv:
1103 case Instruction::FDiv:
1104 printBinaryInstruction("div",Left,Right);
1105 break;
1106 case Instruction::URem:
1107 printBinaryInstruction("rem.un",Left,Right);
1108 break;
1109 case Instruction::SRem:
1110 case Instruction::FRem:
1111 printBinaryInstruction("rem",Left,Right);
1112 break;
1113 // Binary Condition
1114 case Instruction::ICmp:
1115 printICmpInstruction(cast<ICmpInst>(Inst)->getPredicate(),Left,Right);
1116 break;
1117 case Instruction::FCmp:
1118 printFCmpInstruction(cast<FCmpInst>(Inst)->getPredicate(),Left,Right);
1119 break;
1120 // Bitwise Binary
1121 case Instruction::And:
1122 printBinaryInstruction("and",Left,Right);
1123 break;
1124 case Instruction::Or:
1125 printBinaryInstruction("or",Left,Right);
1126 break;
1127 case Instruction::Xor:
1128 printBinaryInstruction("xor",Left,Right);
1129 break;
1130 case Instruction::Shl:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001131 printValueLoad(Left);
1132 printValueLoad(Right);
1133 printSimpleInstruction("conv.i4");
1134 printSimpleInstruction("shl");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001135 break;
1136 case Instruction::LShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001137 printValueLoad(Left);
1138 printValueLoad(Right);
1139 printSimpleInstruction("conv.i4");
1140 printSimpleInstruction("shr.un");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001141 break;
1142 case Instruction::AShr:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001143 printValueLoad(Left);
1144 printValueLoad(Right);
1145 printSimpleInstruction("conv.i4");
1146 printSimpleInstruction("shr");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001147 break;
1148 case Instruction::Select:
1149 printSelectInstruction(Inst->getOperand(0),Inst->getOperand(1),Inst->getOperand(2));
1150 break;
1151 case Instruction::Load:
1152 printIndirectLoad(Inst->getOperand(0));
1153 break;
1154 case Instruction::Store:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001155 printIndirectSave(Inst->getOperand(1), Inst->getOperand(0));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001156 break;
Anton Korobeynikov94ac0342009-07-14 09:53:14 +00001157 case Instruction::SExt:
1158 printCastInstruction(Inst->getOpcode(),Left,
1159 cast<CastInst>(Inst)->getDestTy(),
1160 cast<CastInst>(Inst)->getSrcTy());
1161 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001162 case Instruction::Trunc:
1163 case Instruction::ZExt:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001164 case Instruction::FPTrunc:
1165 case Instruction::FPExt:
1166 case Instruction::UIToFP:
1167 case Instruction::SIToFP:
1168 case Instruction::FPToUI:
1169 case Instruction::FPToSI:
1170 case Instruction::PtrToInt:
1171 case Instruction::IntToPtr:
1172 case Instruction::BitCast:
1173 printCastInstruction(Inst->getOpcode(),Left,
1174 cast<CastInst>(Inst)->getDestTy());
1175 break;
1176 case Instruction::GetElementPtr:
1177 printGepInstruction(Inst->getOperand(0),gep_type_begin(Inst),
1178 gep_type_end(Inst));
1179 break;
1180 case Instruction::Call:
1181 printCallInstruction(cast<CallInst>(Inst));
1182 break;
1183 case Instruction::Invoke:
1184 printInvokeInstruction(cast<InvokeInst>(Inst));
1185 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001186 case Instruction::Unwind:
1187 printSimpleInstruction("newobj",
1188 "instance void [mscorlib]System.Exception::.ctor()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001189 printSimpleInstruction("throw");
1190 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001191 case Instruction::Switch:
1192 printSwitchInstruction(cast<SwitchInst>(Inst));
1193 break;
1194 case Instruction::Alloca:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001195 printAllocaInstruction(cast<AllocaInst>(Inst));
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001196 break;
1197 case Instruction::Malloc:
Torok Edwinc23197a2009-07-14 16:55:14 +00001198 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001199 break;
1200 case Instruction::Free:
Torok Edwinc23197a2009-07-14 16:55:14 +00001201 llvm_unreachable("LowerAllocationsPass used");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001202 break;
1203 case Instruction::Unreachable:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001204 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
1205 printSimpleInstruction("newobj",
1206 "instance void [mscorlib]System.Exception::.ctor(string)");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001207 printSimpleInstruction("throw");
1208 break;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001209 case Instruction::VAArg:
1210 printVAArgInstruction(cast<VAArgInst>(Inst));
1211 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001212 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001213 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001214 llvm_unreachable("Unsupported instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001215 }
1216}
1217
1218
1219void MSILWriter::printLoop(const Loop* L) {
1220 Out << getLabelName(L->getHeader()->getName()) << ":\n";
1221 const std::vector<BasicBlock*>& blocks = L->getBlocks();
1222 for (unsigned I = 0, E = blocks.size(); I!=E; I++) {
1223 BasicBlock* BB = blocks[I];
1224 Loop* BBLoop = LInfo->getLoopFor(BB);
1225 if (BBLoop == L)
1226 printBasicBlock(BB);
1227 else if (BB==BBLoop->getHeader() && BBLoop->getParentLoop()==L)
1228 printLoop(BBLoop);
1229 }
1230 printSimpleInstruction("br",getLabelName(L->getHeader()->getName()).c_str());
1231}
1232
1233
1234void MSILWriter::printBasicBlock(const BasicBlock* BB) {
1235 Out << getLabelName(BB) << ":\n";
1236 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1237 const Instruction* Inst = I;
1238 // Comment llvm original instruction
Owen Andersoncb371882008-08-21 00:14:44 +00001239 // Out << "\n//" << *Inst << "\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001240 // Do not handle PHI instruction in current block
1241 if (Inst->getOpcode()==Instruction::PHI) continue;
1242 // Print instruction
1243 printInstruction(Inst);
1244 // Save result
1245 if (Inst->getType()!=Type::VoidTy) {
1246 // Do not save value after invoke, it done in "try" block
1247 if (Inst->getOpcode()==Instruction::Invoke) continue;
1248 printValueSave(Inst);
1249 }
1250 }
1251}
1252
1253
1254void MSILWriter::printLocalVariables(const Function& F) {
1255 std::string Name;
1256 const Type* Ty = NULL;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001257 std::set<const Value*> Printed;
1258 const Value* VaList = NULL;
1259 unsigned StackDepth = 8;
1260 // Find local variables
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001261 for (const_inst_iterator I = inst_begin(&F), E = inst_end(&F); I!=E; ++I) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001262 if (I->getOpcode()==Instruction::Call ||
1263 I->getOpcode()==Instruction::Invoke) {
1264 // Test stack depth.
1265 if (StackDepth<I->getNumOperands())
1266 StackDepth = I->getNumOperands();
1267 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001268 const AllocaInst* AI = dyn_cast<AllocaInst>(&*I);
1269 if (AI && !isa<GlobalVariable>(AI)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001270 // Local variable allocation.
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001271 Ty = PointerType::getUnqual(AI->getAllocatedType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001272 Name = getValueName(AI);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001273 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001274 } else if (I->getType()!=Type::VoidTy) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001275 // Operation result.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001276 Ty = I->getType();
1277 Name = getValueName(&*I);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001278 Out << "\t.locals (" << getTypeName(Ty) << Name << ")\n";
1279 }
1280 // Test on 'va_list' variable
1281 bool isVaList = false;
1282 if (const VAArgInst* VaInst = dyn_cast<VAArgInst>(&*I)) {
1283 // "va_list" as "va_arg" instruction operand.
1284 isVaList = true;
1285 VaList = VaInst->getOperand(0);
1286 } else if (const IntrinsicInst* Inst = dyn_cast<IntrinsicInst>(&*I)) {
1287 // "va_list" as intrinsic function operand.
1288 switch (Inst->getIntrinsicID()) {
1289 case Intrinsic::vastart:
1290 case Intrinsic::vaend:
1291 case Intrinsic::vacopy:
1292 isVaList = true;
1293 VaList = Inst->getOperand(1);
1294 break;
1295 default:
1296 isVaList = false;
1297 }
1298 }
1299 // Print "va_list" variable.
1300 if (isVaList && Printed.insert(VaList).second) {
1301 Name = getValueName(VaList);
1302 Name.insert(Name.length()-1,"$valist");
1303 Out << "\t.locals (valuetype [mscorlib]System.ArgIterator "
1304 << Name << ")\n";
1305 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001306 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001307 printSimpleInstruction(".maxstack",utostr(StackDepth*2).c_str());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001308}
1309
1310
1311void MSILWriter::printFunctionBody(const Function& F) {
1312 // Print body
1313 for (Function::const_iterator I = F.begin(), E = F.end(); I!=E; ++I) {
1314 if (Loop *L = LInfo->getLoopFor(I)) {
1315 if (L->getHeader()==I && L->getParentLoop()==0)
1316 printLoop(L);
1317 } else {
1318 printBasicBlock(I);
1319 }
1320 }
1321}
1322
1323
1324void MSILWriter::printConstantExpr(const ConstantExpr* CE) {
1325 const Value *left = 0, *right = 0;
1326 if (CE->getNumOperands()>=1) left = CE->getOperand(0);
1327 if (CE->getNumOperands()>=2) right = CE->getOperand(1);
1328 // Print instruction
1329 switch (CE->getOpcode()) {
1330 case Instruction::Trunc:
1331 case Instruction::ZExt:
1332 case Instruction::SExt:
1333 case Instruction::FPTrunc:
1334 case Instruction::FPExt:
1335 case Instruction::UIToFP:
1336 case Instruction::SIToFP:
1337 case Instruction::FPToUI:
1338 case Instruction::FPToSI:
1339 case Instruction::PtrToInt:
1340 case Instruction::IntToPtr:
1341 case Instruction::BitCast:
1342 printCastInstruction(CE->getOpcode(),left,CE->getType());
1343 break;
1344 case Instruction::GetElementPtr:
1345 printGepInstruction(CE->getOperand(0),gep_type_begin(CE),gep_type_end(CE));
1346 break;
1347 case Instruction::ICmp:
1348 printICmpInstruction(CE->getPredicate(),left,right);
1349 break;
1350 case Instruction::FCmp:
1351 printFCmpInstruction(CE->getPredicate(),left,right);
1352 break;
1353 case Instruction::Select:
1354 printSelectInstruction(CE->getOperand(0),CE->getOperand(1),CE->getOperand(2));
1355 break;
1356 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001357 case Instruction::FAdd:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001358 printBinaryInstruction("add",left,right);
1359 break;
1360 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001361 case Instruction::FSub:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001362 printBinaryInstruction("sub",left,right);
1363 break;
1364 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001365 case Instruction::FMul:
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001366 printBinaryInstruction("mul",left,right);
1367 break;
1368 case Instruction::UDiv:
1369 printBinaryInstruction("div.un",left,right);
1370 break;
1371 case Instruction::SDiv:
1372 case Instruction::FDiv:
1373 printBinaryInstruction("div",left,right);
1374 break;
1375 case Instruction::URem:
1376 printBinaryInstruction("rem.un",left,right);
1377 break;
1378 case Instruction::SRem:
1379 case Instruction::FRem:
1380 printBinaryInstruction("rem",left,right);
1381 break;
1382 case Instruction::And:
1383 printBinaryInstruction("and",left,right);
1384 break;
1385 case Instruction::Or:
1386 printBinaryInstruction("or",left,right);
1387 break;
1388 case Instruction::Xor:
1389 printBinaryInstruction("xor",left,right);
1390 break;
1391 case Instruction::Shl:
1392 printBinaryInstruction("shl",left,right);
1393 break;
1394 case Instruction::LShr:
1395 printBinaryInstruction("shr.un",left,right);
1396 break;
1397 case Instruction::AShr:
1398 printBinaryInstruction("shr",left,right);
1399 break;
1400 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001401 errs() << "Expression = " << *CE << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001402 llvm_unreachable("Invalid constant expression");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001403 }
1404}
1405
1406
1407void MSILWriter::printStaticInitializerList() {
1408 // List of global variables with uninitialized fields.
1409 for (std::map<const GlobalVariable*,std::vector<StaticInitializer> >::iterator
1410 VarI = StaticInitList.begin(), VarE = StaticInitList.end(); VarI!=VarE;
1411 ++VarI) {
1412 const std::vector<StaticInitializer>& InitList = VarI->second;
1413 if (InitList.empty()) continue;
1414 // For each uninitialized field.
1415 for (std::vector<StaticInitializer>::const_iterator I = InitList.begin(),
1416 E = InitList.end(); I!=E; ++I) {
1417 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(I->constant)) {
Owen Andersoncb371882008-08-21 00:14:44 +00001418 // Out << "\n// Init " << getValueName(VarI->first) << ", offset " <<
1419 // utostr(I->offset) << ", type "<< *I->constant->getType() << "\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001420 // Load variable address
1421 printValueLoad(VarI->first);
1422 // Add offset
1423 if (I->offset!=0) {
1424 printPtrLoad(I->offset);
1425 printSimpleInstruction("add");
1426 }
1427 // Load value
1428 printConstantExpr(CE);
1429 // Save result at offset
1430 std::string postfix = getTypePostfix(CE->getType(),true);
1431 if (*postfix.begin()=='u') *postfix.begin() = 'i';
1432 postfix = "stind."+postfix;
1433 printSimpleInstruction(postfix.c_str());
1434 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001435 errs() << "Constant = " << *I->constant << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001436 llvm_unreachable("Invalid static initializer");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001437 }
1438 }
1439 }
1440}
1441
1442
1443void MSILWriter::printFunction(const Function& F) {
Devang Patel05988662008-09-25 21:00:45 +00001444 bool isSigned = F.paramHasAttr(0, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001445 Out << "\n.method static ";
Rafael Espindolabb46f522009-01-15 20:18:42 +00001446 Out << (F.hasLocalLinkage() ? "private " : "public ");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001447 if (F.isVarArg()) Out << "vararg ";
1448 Out << getTypeName(F.getReturnType(),isSigned) <<
1449 getConvModopt(F.getCallingConv()) << getValueName(&F) << '\n';
1450 // Arguments
1451 Out << "\t(";
1452 unsigned ArgIdx = 1;
1453 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I!=E;
1454 ++I, ++ArgIdx) {
Devang Patel05988662008-09-25 21:00:45 +00001455 isSigned = F.paramHasAttr(ArgIdx, Attribute::SExt);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001456 if (I!=F.arg_begin()) Out << ", ";
1457 Out << getTypeName(I->getType(),isSigned) << getValueName(I);
1458 }
1459 Out << ") cil managed\n";
1460 // Body
1461 Out << "{\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001462 printLocalVariables(F);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001463 printFunctionBody(F);
1464 Out << "}\n";
1465}
1466
1467
1468void MSILWriter::printDeclarations(const TypeSymbolTable& ST) {
1469 std::string Name;
1470 std::set<const Type*> Printed;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001471 for (std::set<const Type*>::const_iterator
1472 UI = UsedTypes->begin(), UE = UsedTypes->end(); UI!=UE; ++UI) {
1473 const Type* Ty = *UI;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001474 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty) || isa<StructType>(Ty))
1475 Name = getTypeName(Ty, false, true);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001476 // Type with no need to declare.
1477 else continue;
1478 // Print not duplicated type
1479 if (Printed.insert(Ty).second) {
1480 Out << ".class value explicit ansi sealed '" << Name << "'";
Duncan Sands777d2302009-05-09 07:06:46 +00001481 Out << " { .pack " << 1 << " .size " << TD->getTypeAllocSize(Ty);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00001482 Out << " }\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001483 }
1484 }
1485}
1486
1487
1488unsigned int MSILWriter::getBitWidth(const Type* Ty) {
1489 unsigned int N = Ty->getPrimitiveSizeInBits();
1490 assert(N!=0 && "Invalid type in getBitWidth()");
1491 switch (N) {
1492 case 1:
1493 case 8:
1494 case 16:
1495 case 32:
1496 case 64:
1497 return N;
1498 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001499 errs() << "Bits = " << N << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001500 llvm_unreachable("Unsupported integer width");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001501 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001502 return 0; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001503}
1504
1505
1506void MSILWriter::printStaticConstant(const Constant* C, uint64_t& Offset) {
1507 uint64_t TySize = 0;
1508 const Type* Ty = C->getType();
1509 // Print zero initialized constant.
1510 if (isa<ConstantAggregateZero>(C) || C->isNullValue()) {
Duncan Sands777d2302009-05-09 07:06:46 +00001511 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001512 Offset += TySize;
1513 Out << "int8 (0) [" << TySize << "]";
1514 return;
1515 }
1516 // Print constant initializer
1517 switch (Ty->getTypeID()) {
1518 case Type::IntegerTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001519 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001520 const ConstantInt* Int = cast<ConstantInt>(C);
1521 Out << getPrimitiveTypeName(Ty,true) << "(" << Int->getSExtValue() << ")";
1522 break;
1523 }
1524 case Type::FloatTyID:
1525 case Type::DoubleTyID: {
Duncan Sands777d2302009-05-09 07:06:46 +00001526 TySize = TD->getTypeAllocSize(Ty);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001527 const ConstantFP* FP = cast<ConstantFP>(C);
1528 if (Ty->getTypeID() == Type::FloatTyID)
Dale Johannesen43421b32007-09-06 18:13:44 +00001529 Out << "int32 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001530 (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001531 else
Dale Johannesen43421b32007-09-06 18:13:44 +00001532 Out << "int64 (" <<
Dale Johannesen7111b022008-10-09 18:53:47 +00001533 FP->getValueAPF().bitcastToAPInt().getZExtValue() << ')';
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001534 break;
1535 }
1536 case Type::ArrayTyID:
1537 case Type::VectorTyID:
1538 case Type::StructTyID:
1539 for (unsigned I = 0, E = C->getNumOperands(); I<E; I++) {
1540 if (I!=0) Out << ",\n";
1541 printStaticConstant(C->getOperand(I),Offset);
1542 }
1543 break;
1544 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +00001545 TySize = TD->getTypeAllocSize(C->getType());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001546 // Initialize with global variable address
1547 if (const GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1548 std::string name = getValueName(G);
1549 Out << "&(" << name.insert(name.length()-1,"$data") << ")";
1550 } else {
1551 // Dynamic initialization
1552 if (!isa<ConstantPointerNull>(C) && !C->isNullValue())
1553 InitListPtr->push_back(StaticInitializer(C,Offset));
1554 // Null pointer initialization
1555 if (TySize==4) Out << "int32 (0)";
1556 else if (TySize==8) Out << "int64 (0)";
Torok Edwinc23197a2009-07-14 16:55:14 +00001557 else llvm_unreachable("Invalid pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001558 }
1559 break;
1560 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001561 errs() << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +00001562 llvm_unreachable("Invalid type in printStaticConstant()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001563 }
1564 // Increase offset.
1565 Offset += TySize;
1566}
1567
1568
1569void MSILWriter::printStaticInitializer(const Constant* C,
1570 const std::string& Name) {
1571 switch (C->getType()->getTypeID()) {
1572 case Type::IntegerTyID:
1573 case Type::FloatTyID:
1574 case Type::DoubleTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001575 Out << getPrimitiveTypeName(C->getType(), false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001576 break;
1577 case Type::ArrayTyID:
1578 case Type::VectorTyID:
1579 case Type::StructTyID:
1580 case Type::PointerTyID:
1581 Out << getTypeName(C->getType());
1582 break;
1583 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001584 errs() << "Type = " << *C << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001585 llvm_unreachable("Invalid constant type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001586 }
1587 // Print initializer
1588 std::string label = Name;
1589 label.insert(label.length()-1,"$data");
1590 Out << Name << " at " << label << '\n';
1591 Out << ".data " << label << " = {\n";
1592 uint64_t offset = 0;
1593 printStaticConstant(C,offset);
1594 Out << "\n}\n\n";
1595}
1596
1597
1598void MSILWriter::printVariableDefinition(const GlobalVariable* G) {
1599 const Constant* C = G->getInitializer();
1600 if (C->isNullValue() || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
1601 InitListPtr = 0;
1602 else
1603 InitListPtr = &StaticInitList[G];
1604 printStaticInitializer(C,getValueName(G));
1605}
1606
1607
1608void MSILWriter::printGlobalVariables() {
1609 if (ModulePtr->global_empty()) return;
1610 Module::global_iterator I,E;
1611 for (I = ModulePtr->global_begin(), E = ModulePtr->global_end(); I!=E; ++I) {
1612 // Variable definition
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001613 Out << ".field static " << (I->isDeclaration() ? "public " :
1614 "private ");
1615 if (I->isDeclaration()) {
1616 Out << getTypeName(I->getType()) << getValueName(&*I) << "\n\n";
1617 } else
1618 printVariableDefinition(&*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001619 }
1620}
1621
1622
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001623const char* MSILWriter::getLibraryName(const Function* F) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001624 return getLibraryForSymbol(F->getName(), true, F->getCallingConv());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001625}
1626
1627
1628const char* MSILWriter::getLibraryName(const GlobalVariable* GV) {
Daniel Dunbarbda96532009-07-21 08:57:31 +00001629 return getLibraryForSymbol(Mang->getMangledName(GV), false, 0);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001630}
1631
1632
Daniel Dunbarbda96532009-07-21 08:57:31 +00001633const char* MSILWriter::getLibraryForSymbol(const StringRef &Name,
1634 bool isFunction,
1635 unsigned CallingConv) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001636 // TODO: Read *.def file with function and libraries definitions.
1637 return "MSVCRT.DLL";
1638}
1639
1640
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001641void MSILWriter::printExternals() {
1642 Module::const_iterator I,E;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001643 // Functions.
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001644 for (I=ModulePtr->begin(),E=ModulePtr->end(); I!=E; ++I) {
1645 // Skip intrisics
Duncan Sandsa3355ff2007-12-03 20:06:50 +00001646 if (I->isIntrinsic()) continue;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001647 if (I->isDeclaration()) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001648 const Function* F = I;
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001649 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001650 std::string Sig =
1651 getCallSignature(cast<FunctionType>(F->getFunctionType()), NULL, Name);
1652 Out << ".method static hidebysig pinvokeimpl(\""
1653 << getLibraryName(F) << "\")\n\t" << Sig << " preservesig {}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001654 }
1655 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001656 // External variables and static initialization.
1657 Out <<
1658 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1659 " native int LoadLibrary(string) preservesig {}\n"
1660 ".method public hidebysig static pinvokeimpl(\"KERNEL32.DLL\" ansi winapi)"
1661 " native int GetProcAddress(native int, string) preservesig {}\n";
1662 Out <<
1663 ".method private static void* $MSIL_Import(string lib,string sym)\n"
1664 " managed cil\n{\n"
1665 "\tldarg\tlib\n"
1666 "\tcall\tnative int LoadLibrary(string)\n"
1667 "\tldarg\tsym\n"
1668 "\tcall\tnative int GetProcAddress(native int,string)\n"
1669 "\tdup\n"
1670 "\tbrtrue\tL_01\n"
1671 "\tldstr\t\"Can no import variable\"\n"
1672 "\tnewobj\tinstance void [mscorlib]System.Exception::.ctor(string)\n"
1673 "\tthrow\n"
1674 "L_01:\n"
1675 "\tret\n"
1676 "}\n\n"
1677 ".method static private void $MSIL_Init() managed cil\n{\n";
1678 printStaticInitializerList();
1679 // Foreach global variable.
1680 for (Module::global_iterator I = ModulePtr->global_begin(),
1681 E = ModulePtr->global_end(); I!=E; ++I) {
1682 if (!I->isDeclaration() || !I->hasDLLImportLinkage()) continue;
1683 // Use "LoadLibrary"/"GetProcAddress" to recive variable address.
1684 std::string Label = "not_null$_"+utostr(getUniqID());
1685 std::string Tmp = getTypeName(I->getType())+getValueName(&*I);
1686 printSimpleInstruction("ldsflda",Tmp.c_str());
1687 Out << "\tldstr\t\"" << getLibraryName(&*I) << "\"\n";
Chris Lattnerb8158ac2009-07-14 18:17:16 +00001688 Out << "\tldstr\t\"" << Mang->getMangledName(&*I) << "\"\n";
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001689 printSimpleInstruction("call","void* $MSIL_Import(string,string)");
1690 printIndirectSave(I->getType());
1691 }
1692 printSimpleInstruction("ret");
1693 Out << "}\n\n";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001694}
1695
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001696
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001697//===----------------------------------------------------------------------===//
Bill Wendling85db3a92008-02-26 10:57:23 +00001698// External Interface declaration
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001699//===----------------------------------------------------------------------===//
1700
David Greene71847812009-07-14 20:18:05 +00001701bool MSILTarget::addPassesToEmitWholeFile(PassManager &PM,
1702 formatted_raw_ostream &o,
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00001703 CodeGenFileType FileType,
Bill Wendling98a366d2009-04-29 23:29:43 +00001704 CodeGenOpt::Level OptLevel)
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001705{
1706 if (FileType != TargetMachine::AssemblyFile) return true;
1707 MSILWriter* Writer = new MSILWriter(o);
Gordon Henriksence224772008-01-07 01:30:38 +00001708 PM.add(createGCLoweringPass());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001709 PM.add(createLowerAllocationsPass(true));
1710 // FIXME: Handle switch trougth native IL instruction "switch"
1711 PM.add(createLowerSwitchPass());
1712 PM.add(createCFGSimplificationPass());
1713 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
1714 PM.add(Writer);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001715 PM.add(createGCInfoDeleter());
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001716 return false;
1717}