blob: fa47a8f1135d8cb42b74e11142f5674a0f2cbf80 [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
Anton Korobeynikov099883f2007-03-21 21:38:25 +000045 virtual const TargetData *getTargetData() const { return &DataLayout; }
46 };
47}
48
Daniel Dunbar0c795d62009-07-25 06:49:55 +000049extern "C" void LLVMInitializeMSILTarget() {
50 // Register the target.
Daniel Dunbare28039c2009-08-02 23:37:13 +000051 RegisterTargetMachineDeprecated<MSILTarget> X(TheMSILTarget);
Daniel Dunbar0c795d62009-07-25 06:49:55 +000052}
Douglas Gregor1555a232009-06-16 20:12:29 +000053
Anton Korobeynikov099883f2007-03-21 21:38:25 +000054bool MSILModule::runOnModule(Module &M) {
55 ModulePtr = &M;
56 TD = &getAnalysis<TargetData>();
57 bool Changed = false;
58 // Find named types.
59 TypeSymbolTable& Table = M.getTypeSymbolTable();
60 std::set<const Type *> Types = getAnalysis<FindUsedTypes>().getTypes();
61 for (TypeSymbolTable::iterator I = Table.begin(), E = Table.end(); I!=E; ) {
62 if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second))
63 Table.remove(I++);
64 else {
65 std::set<const Type *>::iterator T = Types.find(I->second);
66 if (T==Types.end())
67 Table.remove(I++);
68 else {
69 Types.erase(T);
70 ++I;
71 }
72 }
73 }
74 // Find unnamed types.
75 unsigned RenameCounter = 0;
76 for (std::set<const Type *>::const_iterator I = Types.begin(),
77 E = Types.end(); I!=E; ++I)
78 if (const StructType *STy = dyn_cast<StructType>(*I)) {
79 while (ModulePtr->addTypeName("unnamed$"+utostr(RenameCounter), STy))
80 ++RenameCounter;
81 Changed = true;
82 }
83 // Pointer for FunctionPass.
84 UsedTypes = &getAnalysis<FindUsedTypes>().getTypes();
85 return Changed;
86}
87
Devang Patel19974732007-05-03 01:11:54 +000088char MSILModule::ID = 0;
89char MSILWriter::ID = 0;
Anton Korobeynikov099883f2007-03-21 21:38:25 +000090
91bool MSILWriter::runOnFunction(Function &F) {
92 if (F.isDeclaration()) return false;
Chris Lattner9062d9a2009-04-17 00:26:12 +000093
94 // Do not codegen any 'available_externally' functions at all, they have
95 // definitions outside the translation unit.
96 if (F.hasAvailableExternallyLinkage())
97 return false;
98
Anton Korobeynikov099883f2007-03-21 21:38:25 +000099 LInfo = &getAnalysis<LoopInfo>();
100 printFunction(F);
101 return false;
102}
103
104
105bool MSILWriter::doInitialization(Module &M) {
106 ModulePtr = &M;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000107 Mang = new Mangler(M);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000108 Out << ".assembly extern mscorlib {}\n";
109 Out << ".assembly MSIL {}\n\n";
110 Out << "// External\n";
111 printExternals();
112 Out << "// Declarations\n";
113 printDeclarations(M.getTypeSymbolTable());
114 Out << "// Definitions\n";
115 printGlobalVariables();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000116 Out << "// Startup code\n";
117 printModuleStartup();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000118 return false;
119}
120
121
122bool MSILWriter::doFinalization(Module &M) {
123 delete Mang;
124 return false;
125}
126
127
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000128void MSILWriter::printModuleStartup() {
129 Out <<
130 ".method static public int32 $MSIL_Startup() {\n"
131 "\t.entrypoint\n"
132 "\t.locals (native int i)\n"
133 "\t.locals (native int argc)\n"
134 "\t.locals (native int ptr)\n"
135 "\t.locals (void* argv)\n"
136 "\t.locals (string[] args)\n"
137 "\tcall\tstring[] [mscorlib]System.Environment::GetCommandLineArgs()\n"
138 "\tdup\n"
139 "\tstloc\targs\n"
140 "\tldlen\n"
141 "\tconv.i4\n"
142 "\tdup\n"
143 "\tstloc\targc\n";
144 printPtrLoad(TD->getPointerSize());
145 Out <<
146 "\tmul\n"
147 "\tlocalloc\n"
148 "\tstloc\targv\n"
149 "\tldc.i4.0\n"
150 "\tstloc\ti\n"
151 "L_01:\n"
152 "\tldloc\ti\n"
153 "\tldloc\targc\n"
154 "\tceq\n"
155 "\tbrtrue\tL_02\n"
156 "\tldloc\targs\n"
157 "\tldloc\ti\n"
158 "\tldelem.ref\n"
159 "\tcall\tnative int [mscorlib]System.Runtime.InteropServices.Marshal::"
160 "StringToHGlobalAnsi(string)\n"
161 "\tstloc\tptr\n"
162 "\tldloc\targv\n"
163 "\tldloc\ti\n";
164 printPtrLoad(TD->getPointerSize());
165 Out <<
166 "\tmul\n"
167 "\tadd\n"
168 "\tldloc\tptr\n"
169 "\tstind.i\n"
170 "\tldloc\ti\n"
171 "\tldc.i4.1\n"
172 "\tadd\n"
173 "\tstloc\ti\n"
174 "\tbr\tL_01\n"
175 "L_02:\n"
176 "\tcall void $MSIL_Init()\n";
177
178 // Call user 'main' function.
179 const Function* F = ModulePtr->getFunction("main");
180 if (!F || F->isDeclaration()) {
181 Out << "\tldc.i4.0\n\tret\n}\n";
182 return;
183 }
Nick Lewycky9c0f1462009-03-19 05:51:39 +0000184 bool BadSig = true;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000185 std::string Args("");
186 Function::const_arg_iterator Arg1,Arg2;
187
188 switch (F->arg_size()) {
189 case 0:
190 BadSig = false;
191 break;
192 case 1:
193 Arg1 = F->arg_begin();
194 if (Arg1->getType()->isInteger()) {
195 Out << "\tldloc\targc\n";
196 Args = getTypeName(Arg1->getType());
197 BadSig = false;
198 }
199 break;
200 case 2:
201 Arg1 = Arg2 = F->arg_begin(); ++Arg2;
202 if (Arg1->getType()->isInteger() &&
203 Arg2->getType()->getTypeID() == Type::PointerTyID) {
204 Out << "\tldloc\targc\n\tldloc\targv\n";
205 Args = getTypeName(Arg1->getType())+","+getTypeName(Arg2->getType());
206 BadSig = false;
207 }
208 break;
209 default:
210 BadSig = true;
211 }
212
213 bool RetVoid = (F->getReturnType()->getTypeID() == Type::VoidTyID);
Anton Korobeynikov7c1c2612008-02-20 11:22:39 +0000214 if (BadSig || (!F->getReturnType()->isInteger() && !RetVoid)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000215 Out << "\tldc.i4.0\n";
216 } else {
217 Out << "\tcall\t" << getTypeName(F->getReturnType()) <<
218 getConvModopt(F->getCallingConv()) << "main(" << Args << ")\n";
219 if (RetVoid)
220 Out << "\tldc.i4.0\n";
221 else
222 Out << "\tconv.i4\n";
223 }
224 Out << "\tret\n}\n";
225}
226
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000227bool MSILWriter::isZeroValue(const Value* V) {
228 if (const Constant *C = dyn_cast<Constant>(V))
229 return C->isNullValue();
230 return false;
231}
232
233
234std::string MSILWriter::getValueName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000235 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000236 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000237 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000238 else {
239 unsigned &No = AnonValueNumbers[V];
240 if (No == 0) No = ++NextAnonValueNumber;
241 Name = "tmp" + utostr(No);
242 }
243
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000244 // Name into the quotes allow control and space characters.
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000245 return "'"+Name+"'";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000246}
247
248
249std::string MSILWriter::getLabelName(const std::string& Name) {
250 if (Name.find('.')!=std::string::npos) {
251 std::string Tmp(Name);
252 // Replace unaccepable characters in the label name.
253 for (std::string::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I)
254 if (*I=='.') *I = '@';
255 return Tmp;
256 }
257 return Name;
258}
259
260
261std::string MSILWriter::getLabelName(const Value* V) {
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000262 std::string Name;
Chris Lattnerc2b443a2009-07-16 04:34:33 +0000263 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Chris Lattnerb8158ac2009-07-14 18:17:16 +0000264 Name = Mang->getMangledName(GV);
Chris Lattnerca1bafd2009-07-13 23:46:46 +0000265 else {
266 unsigned &No = AnonValueNumbers[V];
267 if (No == 0) No = ++NextAnonValueNumber;
268 Name = "tmp" + utostr(No);
269 }
270
271 return getLabelName(Name);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000272}
273
274
275std::string MSILWriter::getConvModopt(unsigned CallingConvID) {
276 switch (CallingConvID) {
277 case CallingConv::C:
278 case CallingConv::Cold:
279 case CallingConv::Fast:
280 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) ";
281 case CallingConv::X86_FastCall:
282 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvFastcall) ";
283 case CallingConv::X86_StdCall:
284 return "modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall) ";
285 default:
286 cerr << "CallingConvID = " << CallingConvID << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000287 llvm_unreachable("Unsupported calling convention");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000288 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000289 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000290}
291
292
293std::string MSILWriter::getArrayTypeName(Type::TypeID TyID, const Type* Ty) {
294 std::string Tmp = "";
295 const Type* ElemTy = Ty;
296 assert(Ty->getTypeID()==TyID && "Invalid type passed");
297 // Walk trought array element types.
298 for (;;) {
299 // Multidimensional array.
300 if (ElemTy->getTypeID()==TyID) {
301 if (const ArrayType* ATy = dyn_cast<ArrayType>(ElemTy))
302 Tmp += utostr(ATy->getNumElements());
303 else if (const VectorType* VTy = dyn_cast<VectorType>(ElemTy))
304 Tmp += utostr(VTy->getNumElements());
305 ElemTy = cast<SequentialType>(ElemTy)->getElementType();
306 }
307 // Base element type found.
308 if (ElemTy->getTypeID()!=TyID) break;
309 Tmp += ",";
310 }
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000311 return getTypeName(ElemTy, false, true)+"["+Tmp+"]";
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000312}
313
314
315std::string MSILWriter::getPrimitiveTypeName(const Type* Ty, bool isSigned) {
316 unsigned NumBits = 0;
317 switch (Ty->getTypeID()) {
318 case Type::VoidTyID:
319 return "void ";
320 case Type::IntegerTyID:
321 NumBits = getBitWidth(Ty);
322 if(NumBits==1)
323 return "bool ";
324 if (!isSigned)
325 return "unsigned int"+utostr(NumBits)+" ";
326 return "int"+utostr(NumBits)+" ";
327 case Type::FloatTyID:
328 return "float32 ";
329 case Type::DoubleTyID:
330 return "float64 ";
331 default:
332 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000333 llvm_unreachable("Invalid primitive type");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000334 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000335 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000336}
337
338
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000339std::string MSILWriter::getTypeName(const Type* Ty, bool isSigned,
340 bool isNested) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000341 if (Ty->isPrimitiveType() || Ty->isInteger())
342 return getPrimitiveTypeName(Ty,isSigned);
343 // FIXME: "OpaqueType" support
344 switch (Ty->getTypeID()) {
345 case Type::PointerTyID:
346 return "void* ";
347 case Type::StructTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000348 if (isNested)
349 return ModulePtr->getTypeName(Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000350 return "valuetype '"+ModulePtr->getTypeName(Ty)+"' ";
351 case Type::ArrayTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000352 if (isNested)
353 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000354 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
355 case Type::VectorTyID:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000356 if (isNested)
357 return getArrayTypeName(Ty->getTypeID(),Ty);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000358 return "valuetype '"+getArrayTypeName(Ty->getTypeID(),Ty)+"' ";
359 default:
360 cerr << "Type = " << *Ty << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000361 llvm_unreachable("Invalid type in getTypeName()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000362 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000363 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000364}
365
366
367MSILWriter::ValueType MSILWriter::getValueLocation(const Value* V) {
368 // Function argument
369 if (isa<Argument>(V))
370 return ArgumentVT;
371 // Function
372 else if (const Function* F = dyn_cast<Function>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000373 return F->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000374 // Variable
375 else if (const GlobalVariable* G = dyn_cast<GlobalVariable>(V))
Rafael Espindolabb46f522009-01-15 20:18:42 +0000376 return G->hasLocalLinkage() ? InternalVT : GlobalVT;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000377 // Constant
378 else if (isa<Constant>(V))
379 return isa<ConstantExpr>(V) ? ConstExprVT : ConstVT;
380 // Local variable
381 return LocalVT;
382}
383
384
385std::string MSILWriter::getTypePostfix(const Type* Ty, bool Expand,
386 bool isSigned) {
387 unsigned NumBits = 0;
388 switch (Ty->getTypeID()) {
389 // Integer constant, expanding for stack operations.
390 case Type::IntegerTyID:
391 NumBits = getBitWidth(Ty);
392 // Expand integer value to "int32" or "int64".
393 if (Expand) return (NumBits<=32 ? "i4" : "i8");
394 if (NumBits==1) return "i1";
395 return (isSigned ? "i" : "u")+utostr(NumBits/8);
396 // Float constant.
397 case Type::FloatTyID:
398 return "r4";
399 case Type::DoubleTyID:
400 return "r8";
401 case Type::PointerTyID:
Duncan Sands777d2302009-05-09 07:06:46 +0000402 return "i"+utostr(TD->getTypeAllocSize(Ty));
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000403 default:
404 cerr << "TypeID = " << Ty->getTypeID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000405 llvm_unreachable("Invalid type in TypeToPostfix()");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000406 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000407 return ""; // Not reached
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000408}
409
410
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000411void MSILWriter::printConvToPtr() {
412 switch (ModulePtr->getPointerSize()) {
413 case Module::Pointer32:
414 printSimpleInstruction("conv.u4");
415 break;
416 case Module::Pointer64:
417 printSimpleInstruction("conv.u8");
418 break;
419 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000420 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000421 }
422}
423
424
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000425void MSILWriter::printPtrLoad(uint64_t N) {
426 switch (ModulePtr->getPointerSize()) {
427 case Module::Pointer32:
428 printSimpleInstruction("ldc.i4",utostr(N).c_str());
429 // FIXME: Need overflow test?
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000430 if (!isUInt32(N)) {
431 cerr << "Value = " << utostr(N) << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000432 llvm_unreachable("32-bit pointer overflowed");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000433 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000434 break;
435 case Module::Pointer64:
436 printSimpleInstruction("ldc.i8",utostr(N).c_str());
437 break;
438 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000439 llvm_unreachable("Module use not supporting pointer size");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000440 }
441}
442
443
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000444void MSILWriter::printValuePtrLoad(const Value* V) {
445 printValueLoad(V);
446 printConvToPtr();
447}
448
449
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000450void MSILWriter::printConstLoad(const Constant* C) {
451 if (const ConstantInt* CInt = dyn_cast<ConstantInt>(C)) {
452 // Integer constant
453 Out << "\tldc." << getTypePostfix(C->getType(),true) << '\t';
454 if (CInt->isMinValue(true))
455 Out << CInt->getSExtValue();
456 else
457 Out << CInt->getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000458 } else if (const ConstantFP* FP = dyn_cast<ConstantFP>(C)) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000459 // Float constant
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000460 uint64_t X;
461 unsigned Size;
462 if (FP->getType()->getTypeID()==Type::FloatTyID) {
Dale Johannesen7111b022008-10-09 18:53:47 +0000463 X = (uint32_t)FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000464 Size = 4;
465 } else {
Dale Johannesen7111b022008-10-09 18:53:47 +0000466 X = FP->getValueAPF().bitcastToAPInt().getZExtValue();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000467 Size = 8;
468 }
469 Out << "\tldc.r" << Size << "\t( " << utohexstr(X) << ')';
470 } else if (isa<UndefValue>(C)) {
471 // Undefined constant value = NULL.
472 printPtrLoad(0);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000473 } else {
474 cerr << "Constant = " << *C << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000475 llvm_unreachable("Invalid constant value");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000476 }
477 Out << '\n';
478}
479
480
481void MSILWriter::printValueLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000482 MSILWriter::ValueType Location = getValueLocation(V);
483 switch (Location) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000484 // Global variable or function address.
485 case GlobalVT:
486 case InternalVT:
487 if (const Function* F = dyn_cast<Function>(V)) {
488 std::string Name = getConvModopt(F->getCallingConv())+getValueName(F);
489 printSimpleInstruction("ldftn",
490 getCallSignature(F->getFunctionType(),NULL,Name).c_str());
491 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000492 std::string Tmp;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000493 const Type* ElemTy = cast<PointerType>(V->getType())->getElementType();
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000494 if (Location==GlobalVT && cast<GlobalVariable>(V)->hasDLLImportLinkage()) {
495 Tmp = "void* "+getValueName(V);
496 printSimpleInstruction("ldsfld",Tmp.c_str());
497 } else {
498 Tmp = getTypeName(ElemTy)+getValueName(V);
499 printSimpleInstruction("ldsflda",Tmp.c_str());
500 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000501 }
502 break;
503 // Function argument.
504 case ArgumentVT:
505 printSimpleInstruction("ldarg",getValueName(V).c_str());
506 break;
507 // Local function variable.
508 case LocalVT:
509 printSimpleInstruction("ldloc",getValueName(V).c_str());
510 break;
511 // Constant value.
512 case ConstVT:
513 if (isa<ConstantPointerNull>(V))
514 printPtrLoad(0);
515 else
516 printConstLoad(cast<Constant>(V));
517 break;
518 // Constant expression.
519 case ConstExprVT:
520 printConstantExpr(cast<ConstantExpr>(V));
521 break;
522 default:
523 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000524 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000525 }
526}
527
528
529void MSILWriter::printValueSave(const Value* V) {
530 switch (getValueLocation(V)) {
531 case ArgumentVT:
532 printSimpleInstruction("starg",getValueName(V).c_str());
533 break;
534 case LocalVT:
535 printSimpleInstruction("stloc",getValueName(V).c_str());
536 break;
537 default:
538 cerr << "Value = " << *V << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000539 llvm_unreachable("Invalid value location");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000540 }
541}
542
543
544void MSILWriter::printBinaryInstruction(const char* Name, const Value* Left,
545 const Value* Right) {
546 printValueLoad(Left);
547 printValueLoad(Right);
548 Out << '\t' << Name << '\n';
549}
550
551
552void MSILWriter::printSimpleInstruction(const char* Inst, const char* Operand) {
553 if(Operand)
554 Out << '\t' << Inst << '\t' << Operand << '\n';
555 else
556 Out << '\t' << Inst << '\n';
557}
558
559
560void MSILWriter::printPHICopy(const BasicBlock* Src, const BasicBlock* Dst) {
561 for (BasicBlock::const_iterator I = Dst->begin(), E = Dst->end();
562 isa<PHINode>(I); ++I) {
563 const PHINode* Phi = cast<PHINode>(I);
564 const Value* Val = Phi->getIncomingValueForBlock(Src);
565 if (isa<UndefValue>(Val)) continue;
566 printValueLoad(Val);
567 printValueSave(Phi);
568 }
569}
570
571
572void MSILWriter::printBranchToBlock(const BasicBlock* CurrBB,
573 const BasicBlock* TrueBB,
574 const BasicBlock* FalseBB) {
575 if (TrueBB==FalseBB) {
576 // "TrueBB" and "FalseBB" destination equals
577 printPHICopy(CurrBB,TrueBB);
578 printSimpleInstruction("pop");
579 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
580 } else if (FalseBB==NULL) {
581 // If "FalseBB" not used the jump have condition
582 printPHICopy(CurrBB,TrueBB);
583 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
584 } else if (TrueBB==NULL) {
585 // If "TrueBB" not used the jump is unconditional
586 printPHICopy(CurrBB,FalseBB);
587 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
588 } else {
589 // Copy PHI instructions for each block
590 std::string TmpLabel;
591 // Print PHI instructions for "TrueBB"
592 if (isa<PHINode>(TrueBB->begin())) {
593 TmpLabel = getLabelName(TrueBB)+"$phi_"+utostr(getUniqID());
594 printSimpleInstruction("brtrue",TmpLabel.c_str());
595 } else {
596 printSimpleInstruction("brtrue",getLabelName(TrueBB).c_str());
597 }
598 // Print PHI instructions for "FalseBB"
599 if (isa<PHINode>(FalseBB->begin())) {
600 printPHICopy(CurrBB,FalseBB);
601 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
602 } else {
603 printSimpleInstruction("br",getLabelName(FalseBB).c_str());
604 }
605 if (isa<PHINode>(TrueBB->begin())) {
606 // Handle "TrueBB" PHI Copy
607 Out << TmpLabel << ":\n";
608 printPHICopy(CurrBB,TrueBB);
609 printSimpleInstruction("br",getLabelName(TrueBB).c_str());
610 }
611 }
612}
613
614
615void MSILWriter::printBranchInstruction(const BranchInst* Inst) {
616 if (Inst->isUnconditional()) {
617 printBranchToBlock(Inst->getParent(),NULL,Inst->getSuccessor(0));
618 } else {
619 printValueLoad(Inst->getCondition());
620 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(0),
621 Inst->getSuccessor(1));
622 }
623}
624
625
626void MSILWriter::printSelectInstruction(const Value* Cond, const Value* VTrue,
627 const Value* VFalse) {
628 std::string TmpLabel = std::string("select$true_")+utostr(getUniqID());
629 printValueLoad(VTrue);
630 printValueLoad(Cond);
631 printSimpleInstruction("brtrue",TmpLabel.c_str());
632 printSimpleInstruction("pop");
633 printValueLoad(VFalse);
634 Out << TmpLabel << ":\n";
635}
636
637
638void MSILWriter::printIndirectLoad(const Value* V) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000639 const Type* Ty = V->getType();
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000640 printValueLoad(V);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000641 if (const PointerType* P = dyn_cast<PointerType>(Ty))
642 Ty = P->getElementType();
643 std::string Tmp = "ldind."+getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000644 printSimpleInstruction(Tmp.c_str());
645}
646
647
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000648void MSILWriter::printIndirectSave(const Value* Ptr, const Value* Val) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000649 printValueLoad(Ptr);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000650 printValueLoad(Val);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000651 printIndirectSave(Val->getType());
652}
653
654
655void MSILWriter::printIndirectSave(const Type* Ty) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000656 // Instruction need signed postfix for any type.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000657 std::string postfix = getTypePostfix(Ty, false);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000658 if (*postfix.begin()=='u') *postfix.begin() = 'i';
659 postfix = "stind."+postfix;
660 printSimpleInstruction(postfix.c_str());
661}
662
663
664void MSILWriter::printCastInstruction(unsigned int Op, const Value* V,
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000665 const Type* Ty, const Type* SrcTy) {
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000666 std::string Tmp("");
667 printValueLoad(V);
668 switch (Op) {
669 // Signed
670 case Instruction::SExt:
Anton Korobeynikov94ac0342009-07-14 09:53:14 +0000671 // If sign extending int, convert first from unsigned to signed
672 // with the same bit size - because otherwise we will loose the sign.
673 if (SrcTy) {
674 Tmp = "conv."+getTypePostfix(SrcTy,false,true);
675 printSimpleInstruction(Tmp.c_str());
676 }
Bill Wendling5f544502009-07-14 18:30:04 +0000677 // FALLTHROUGH
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000678 case Instruction::SIToFP:
679 case Instruction::FPToSI:
680 Tmp = "conv."+getTypePostfix(Ty,false,true);
681 printSimpleInstruction(Tmp.c_str());
682 break;
683 // Unsigned
684 case Instruction::FPTrunc:
685 case Instruction::FPExt:
686 case Instruction::UIToFP:
687 case Instruction::Trunc:
688 case Instruction::ZExt:
689 case Instruction::FPToUI:
690 case Instruction::PtrToInt:
691 case Instruction::IntToPtr:
692 Tmp = "conv."+getTypePostfix(Ty,false);
693 printSimpleInstruction(Tmp.c_str());
694 break;
695 // Do nothing
696 case Instruction::BitCast:
697 // FIXME: meaning that ld*/st* instruction do not change data format.
698 break;
699 default:
700 cerr << "Opcode = " << Op << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000701 llvm_unreachable("Invalid conversion instruction");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000702 }
703}
704
705
706void MSILWriter::printGepInstruction(const Value* V, gep_type_iterator I,
707 gep_type_iterator E) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000708 unsigned Size;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000709 // Load address
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000710 printValuePtrLoad(V);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000711 // Calculate element offset.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000712 for (; I!=E; ++I){
713 Size = 0;
714 const Value* IndexValue = I.getOperand();
715 if (const StructType* StrucTy = dyn_cast<StructType>(*I)) {
716 uint64_t FieldIndex = cast<ConstantInt>(IndexValue)->getZExtValue();
717 // Offset is the sum of all previous structure fields.
718 for (uint64_t F = 0; F<FieldIndex; ++F)
Duncan Sands777d2302009-05-09 07:06:46 +0000719 Size += TD->getTypeAllocSize(StrucTy->getContainedType((unsigned)F));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000720 printPtrLoad(Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000721 printSimpleInstruction("add");
722 continue;
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000723 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(*I)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000724 Size = TD->getTypeAllocSize(SeqTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000725 } else {
Duncan Sands777d2302009-05-09 07:06:46 +0000726 Size = TD->getTypeAllocSize(*I);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000727 }
728 // Add offset of current element to stack top.
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000729 if (!isZeroValue(IndexValue)) {
730 // Constant optimization.
731 if (const ConstantInt* C = dyn_cast<ConstantInt>(IndexValue)) {
732 if (C->getValue().isNegative()) {
733 printPtrLoad(C->getValue().abs().getZExtValue()*Size);
734 printSimpleInstruction("sub");
735 continue;
736 } else
737 printPtrLoad(C->getZExtValue()*Size);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000738 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000739 printPtrLoad(Size);
740 printValuePtrLoad(IndexValue);
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000741 printSimpleInstruction("mul");
742 }
743 printSimpleInstruction("add");
744 }
745 }
746}
747
748
749std::string MSILWriter::getCallSignature(const FunctionType* Ty,
750 const Instruction* Inst,
751 std::string Name) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000752 std::string Tmp("");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000753 if (Ty->isVarArg()) Tmp += "vararg ";
754 // Name and return type.
755 Tmp += getTypeName(Ty->getReturnType())+Name+"(";
756 // Function argument type list.
757 unsigned NumParams = Ty->getNumParams();
758 for (unsigned I = 0; I!=NumParams; ++I) {
759 if (I!=0) Tmp += ",";
760 Tmp += getTypeName(Ty->getParamType(I));
761 }
762 // CLR needs to know the exact amount of parameters received by vararg
763 // function, because caller cleans the stack.
764 if (Ty->isVarArg() && Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000765 // Origin to function arguments in "CallInst" or "InvokeInst".
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000766 unsigned Org = isa<InvokeInst>(Inst) ? 3 : 1;
767 // Print variable argument types.
768 unsigned NumOperands = Inst->getNumOperands()-Org;
769 if (NumParams<NumOperands) {
770 if (NumParams!=0) Tmp += ", ";
771 Tmp += "... , ";
772 for (unsigned J = NumParams; J!=NumOperands; ++J) {
773 if (J!=NumParams) Tmp += ", ";
774 Tmp += getTypeName(Inst->getOperand(J+Org)->getType());
775 }
776 }
777 }
778 return Tmp+")";
779}
780
781
782void MSILWriter::printFunctionCall(const Value* FnVal,
783 const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000784 // Get function calling convention.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000785 std::string Name = "";
786 if (const CallInst* Call = dyn_cast<CallInst>(Inst))
787 Name = getConvModopt(Call->getCallingConv());
788 else if (const InvokeInst* Invoke = dyn_cast<InvokeInst>(Inst))
789 Name = getConvModopt(Invoke->getCallingConv());
790 else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000791 errs() << "Instruction = " << Inst->getName() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000792 llvm_unreachable("Need \"Invoke\" or \"Call\" instruction only");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000793 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000794 if (const Function* F = dyn_cast<Function>(FnVal)) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000795 // Direct call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000796 Name += getValueName(F);
797 printSimpleInstruction("call",
798 getCallSignature(F->getFunctionType(),Inst,Name).c_str());
799 } else {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000800 // Indirect function call.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000801 const PointerType* PTy = cast<PointerType>(FnVal->getType());
802 const FunctionType* FTy = cast<FunctionType>(PTy->getElementType());
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000803 // Load function address.
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000804 printValueLoad(FnVal);
805 printSimpleInstruction("calli",getCallSignature(FTy,Inst,Name).c_str());
806 }
807}
808
809
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000810void MSILWriter::printIntrinsicCall(const IntrinsicInst* Inst) {
811 std::string Name;
812 switch (Inst->getIntrinsicID()) {
813 case Intrinsic::vastart:
814 Name = getValueName(Inst->getOperand(1));
815 Name.insert(Name.length()-1,"$valist");
816 // Obtain the argument handle.
817 printSimpleInstruction("ldloca",Name.c_str());
818 printSimpleInstruction("arglist");
819 printSimpleInstruction("call",
820 "instance void [mscorlib]System.ArgIterator::.ctor"
821 "(valuetype [mscorlib]System.RuntimeArgumentHandle)");
822 // Save as pointer type "void*"
823 printValueLoad(Inst->getOperand(1));
824 printSimpleInstruction("ldloca",Name.c_str());
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000825 printIndirectSave(PointerType::getUnqual(IntegerType::get(8)));
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000826 break;
827 case Intrinsic::vaend:
828 // Close argument list handle.
829 printIndirectLoad(Inst->getOperand(1));
830 printSimpleInstruction("call","instance void [mscorlib]System.ArgIterator::End()");
831 break;
832 case Intrinsic::vacopy:
833 // Copy "ArgIterator" valuetype.
834 printIndirectLoad(Inst->getOperand(1));
835 printIndirectLoad(Inst->getOperand(2));
836 printSimpleInstruction("cpobj","[mscorlib]System.ArgIterator");
837 break;
838 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000839 errs() << "Intrinsic ID = " << Inst->getIntrinsicID() << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000840 llvm_unreachable("Invalid intrinsic function");
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000841 }
842}
843
844
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000845void MSILWriter::printCallInstruction(const Instruction* Inst) {
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000846 if (isa<IntrinsicInst>(Inst)) {
847 // Handle intrinsic function.
848 printIntrinsicCall(cast<IntrinsicInst>(Inst));
849 } else {
850 // Load arguments to stack and call function.
851 for (int I = 1, E = Inst->getNumOperands(); I!=E; ++I)
852 printValueLoad(Inst->getOperand(I));
853 printFunctionCall(Inst->getOperand(0),Inst);
854 }
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000855}
856
857
858void MSILWriter::printICmpInstruction(unsigned Predicate, const Value* Left,
859 const Value* Right) {
860 switch (Predicate) {
861 case ICmpInst::ICMP_EQ:
862 printBinaryInstruction("ceq",Left,Right);
863 break;
864 case ICmpInst::ICMP_NE:
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000865 // Emulate = not neg (Op1 eq Op2)
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000866 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000867 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000868 printSimpleInstruction("not");
869 break;
870 case ICmpInst::ICMP_ULE:
871 case ICmpInst::ICMP_SLE:
872 // Emulate = (Op1 eq Op2) or (Op1 lt Op2)
873 printBinaryInstruction("ceq",Left,Right);
874 if (Predicate==ICmpInst::ICMP_ULE)
875 printBinaryInstruction("clt.un",Left,Right);
876 else
877 printBinaryInstruction("clt",Left,Right);
878 printSimpleInstruction("or");
879 break;
880 case ICmpInst::ICMP_UGE:
881 case ICmpInst::ICMP_SGE:
882 // Emulate = (Op1 eq Op2) or (Op1 gt Op2)
883 printBinaryInstruction("ceq",Left,Right);
884 if (Predicate==ICmpInst::ICMP_UGE)
885 printBinaryInstruction("cgt.un",Left,Right);
886 else
887 printBinaryInstruction("cgt",Left,Right);
888 printSimpleInstruction("or");
889 break;
890 case ICmpInst::ICMP_ULT:
891 printBinaryInstruction("clt.un",Left,Right);
892 break;
893 case ICmpInst::ICMP_SLT:
894 printBinaryInstruction("clt",Left,Right);
895 break;
896 case ICmpInst::ICMP_UGT:
897 printBinaryInstruction("cgt.un",Left,Right);
Anton Korobeynikove9fd67e2009-07-14 09:52:47 +0000898 break;
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000899 case ICmpInst::ICMP_SGT:
900 printBinaryInstruction("cgt",Left,Right);
901 break;
902 default:
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000903 errs() << "Predicate = " << Predicate << '\n';
Torok Edwinc23197a2009-07-14 16:55:14 +0000904 llvm_unreachable("Invalid icmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000905 }
906}
907
908
909void MSILWriter::printFCmpInstruction(unsigned Predicate, const Value* Left,
910 const Value* Right) {
911 // FIXME: Correct comparison
912 std::string NanFunc = "bool [mscorlib]System.Double::IsNaN(float64)";
913 switch (Predicate) {
914 case FCmpInst::FCMP_UGT:
915 // X > Y || llvm_fcmp_uno(X, Y)
916 printBinaryInstruction("cgt",Left,Right);
917 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
918 printSimpleInstruction("or");
919 break;
920 case FCmpInst::FCMP_OGT:
921 // X > Y
922 printBinaryInstruction("cgt",Left,Right);
923 break;
924 case FCmpInst::FCMP_UGE:
925 // X >= Y || llvm_fcmp_uno(X, Y)
926 printBinaryInstruction("ceq",Left,Right);
927 printBinaryInstruction("cgt",Left,Right);
928 printSimpleInstruction("or");
929 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
930 printSimpleInstruction("or");
931 break;
932 case FCmpInst::FCMP_OGE:
933 // X >= Y
934 printBinaryInstruction("ceq",Left,Right);
935 printBinaryInstruction("cgt",Left,Right);
936 printSimpleInstruction("or");
937 break;
938 case FCmpInst::FCMP_ULT:
939 // X < Y || llvm_fcmp_uno(X, Y)
940 printBinaryInstruction("clt",Left,Right);
941 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
942 printSimpleInstruction("or");
943 break;
944 case FCmpInst::FCMP_OLT:
945 // X < Y
946 printBinaryInstruction("clt",Left,Right);
947 break;
948 case FCmpInst::FCMP_ULE:
949 // X <= Y || llvm_fcmp_uno(X, Y)
950 printBinaryInstruction("ceq",Left,Right);
951 printBinaryInstruction("clt",Left,Right);
952 printSimpleInstruction("or");
953 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
954 printSimpleInstruction("or");
955 break;
956 case FCmpInst::FCMP_OLE:
957 // X <= Y
958 printBinaryInstruction("ceq",Left,Right);
959 printBinaryInstruction("clt",Left,Right);
960 printSimpleInstruction("or");
961 break;
962 case FCmpInst::FCMP_UEQ:
963 // X == Y || llvm_fcmp_uno(X, Y)
964 printBinaryInstruction("ceq",Left,Right);
965 printFCmpInstruction(FCmpInst::FCMP_UNO,Left,Right);
966 printSimpleInstruction("or");
967 break;
968 case FCmpInst::FCMP_OEQ:
969 // X == Y
970 printBinaryInstruction("ceq",Left,Right);
971 break;
972 case FCmpInst::FCMP_UNE:
973 // X != Y
974 printBinaryInstruction("ceq",Left,Right);
Anton Korobeynikovf13090c2007-05-06 20:13:33 +0000975 printSimpleInstruction("neg");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000976 printSimpleInstruction("not");
977 break;
978 case FCmpInst::FCMP_ONE:
979 // X != Y && llvm_fcmp_ord(X, Y)
980 printBinaryInstruction("ceq",Left,Right);
981 printSimpleInstruction("not");
982 break;
983 case FCmpInst::FCMP_ORD:
984 // return X == X && Y == Y
985 printBinaryInstruction("ceq",Left,Left);
986 printBinaryInstruction("ceq",Right,Right);
987 printSimpleInstruction("or");
988 break;
989 case FCmpInst::FCMP_UNO:
990 // X != X || Y != Y
991 printBinaryInstruction("ceq",Left,Left);
992 printSimpleInstruction("not");
993 printBinaryInstruction("ceq",Right,Right);
994 printSimpleInstruction("not");
995 printSimpleInstruction("or");
996 break;
997 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000998 llvm_unreachable("Illegal FCmp predicate");
Anton Korobeynikov099883f2007-03-21 21:38:25 +0000999 }
1000}
1001
1002
1003void MSILWriter::printInvokeInstruction(const InvokeInst* Inst) {
1004 std::string Label = "leave$normal_"+utostr(getUniqID());
1005 Out << ".try {\n";
1006 // Load arguments
1007 for (int I = 3, E = Inst->getNumOperands(); I!=E; ++I)
1008 printValueLoad(Inst->getOperand(I));
1009 // Print call instruction
1010 printFunctionCall(Inst->getOperand(0),Inst);
1011 // Save function result and leave "try" block
1012 printValueSave(Inst);
1013 printSimpleInstruction("leave",Label.c_str());
1014 Out << "}\n";
1015 Out << "catch [mscorlib]System.Exception {\n";
1016 // Redirect to unwind block
1017 printSimpleInstruction("pop");
1018 printBranchToBlock(Inst->getParent(),NULL,Inst->getUnwindDest());
1019 Out << "}\n" << Label << ":\n";
1020 // Redirect to continue block
1021 printBranchToBlock(Inst->getParent(),NULL,Inst->getNormalDest());
1022}
1023
1024
1025void MSILWriter::printSwitchInstruction(const SwitchInst* Inst) {
1026 // FIXME: Emulate with IL "switch" instruction
1027 // Emulate = if () else if () else if () else ...
1028 for (unsigned int I = 1, E = Inst->getNumCases(); I!=E; ++I) {
1029 printValueLoad(Inst->getCondition());
1030 printValueLoad(Inst->getCaseValue(I));
1031 printSimpleInstruction("ceq");
1032 // Condition jump to successor block
1033 printBranchToBlock(Inst->getParent(),Inst->getSuccessor(I),NULL);
1034 }
1035 // Jump to default block
1036 printBranchToBlock(Inst->getParent(),NULL,Inst->getDefaultDest());
1037}
1038
1039
Anton Korobeynikovf13090c2007-05-06 20:13:33 +00001040void MSILWriter::printVAArgInstruction(const VAArgInst* Inst) {
1041 printIndirectLoad(Inst->getOperand(0));
1042 printSimpleInstruction("call",
1043 "instance typedref [mscorlib]System.ArgIterator::GetNextArg()");
1044 printSimpleInstruction("refanyval","void*");
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001045 std::string Name =
1046 "ldind."+getTypePostfix(PointerType::getUnqual(IntegerType::get(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
1242 if (Inst->getType()!=Type::VoidTy) {
1243 // 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";
Anton Korobeynikov099883f2007-03-21 21:38:25 +00001271 } else if (I->getType()!=Type::VoidTy) {
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}