1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
|
/*
* System.Reflection.Emit-like API for writing .NET assemblies to MSIL
*/
package ch.epfl.lamp.compiler.msil.emit
import ch.epfl.lamp.compiler.msil._
import ch.epfl.lamp.compiler.msil.util.Table
import java.util.ArrayList
import java.util.Stack
import java.util.Iterator
import java.util.Map
import java.util.HashMap
import java.io.IOException
import ILGenerator._
/**
* Generates Microsoft intermediate language (MSIL) instructions.
*
* @author Nikolay Mihaylov
* @version 1.0
*/
final class ILGenerator(_owner: MethodBase) extends Visitable {
//##########################################################################
// public interface
/**
* Puts the specified instruction onto the stream of instructions.
*/
def Emit(opcode: OpCode) {
// switch opcode
if (opcode == OpCode.Ret) {
emit(opcode, null, 0)
} else {
emit(opcode, null)
}
}
/**
* Puts the specified instruction and character argument onto
* the Microsoft intermediate language (MSIL) stream of instructions.
*/
def Emit(opcode: OpCode, arg: Char) {
emit(opcode,new Character(arg))
}
/**
* Puts the specified instruction and metadata token for the
* specified constructor onto the Microsoft intermediate language
* (MSIL) stream of instructions.
*/
def Emit(opcode: OpCode, arg: ConstructorInfo) {
assert(arg != null)
// newobj
// pop size is the number of parameters
emit(opcode,arg, OpCode.PUSH_size(opcode.CEE_push) -
arg.GetParameters().length)
}
/**
* Puts the specified instruction onto the Microsoft intermediate language (MSIL)
* stream followed by the index of the given local variable.
*/
def Emit(opcode: OpCode, arg: LocalBuilder) {
assert(arg != null)
// ldarg | ldarg.s | ldarga
// ldarga.s | ldloc | ldloc.s | ldloca
// ldloca.s | starg | starg.s | stloc
// stloc.s
// <instr_var> <localname>
emit(opcode, arg)
}
/**
* Puts the specified instruction and numerical argument onto
* the Microsoft intermediate language (MSIL) stream of instructions.
*/
def Emit(opcode: OpCode, arg: Double) {
// ldc.r4 | ldc.r8
emit(opcode, new java.lang.Double(arg))
}
/**
* Puts the specified instruction and metadata token for the
* specified field onto the Microsoft intermediate language (MSIL)
* stream of instructions.
*/
def Emit(opcode: OpCode,arg: FieldInfo) {
assert(arg != null)
// ldfld | ldflda | ldsfld | ldsflda | stfld | stsfld
emit(opcode,arg)
}
/**
* Puts the specified instruction and numerical argument onto
* the Microsoft intermediate language (MSIL) stream of instructions.
*/
def Emit(opcode: OpCode, arg: Short ) {
emit(opcode, new java.lang.Short(arg))
}
/**
* Puts the specified instruction and numerical argument onto
* the Microsoft intermediate language (MSIL) stream of instructions.
*/
def Emit(opcode: OpCode, arg: Int) {
// ldc.i4 | ldc.i4.s | unaligned
emit(opcode, new java.lang.Integer(arg))
}
/**
* Puts the specified instruction and numerical argument onto
* the Microsoft intermediate language (MSIL) stream of instructions.
*/
def Emit(opcode: OpCode, arg: Long) {
// ldc.i8
emit(opcode, new java.lang.Long(arg))
}
/**
* Puts the specified instruction onto the Microsoft intermediate
* language (MSIL) stream and leaves space to include a label when
* fixes are done.
*/
def Emit(opcode: OpCode,label: Label) {
assert(label != null)
// beq | beq.s | bge | bge.s |
// bge.un | bge.un.s | bgt | bgt.s | bgt.un | bgt.un.s |
// ble | ble.s | ble.un | ble.un.s | blt | blt.s |
// blt.un | blt.un.s | bne.un | bne.un.s | br | br.s |
// brfalse | brfalse.s | brtrue | brtrue.s | leave | leave.s
emit(opcode, label)
// is the label initialized ? if true backward jump else forward jump
if (label.isInitialized()) {
// if (arg.stacksize != lastLabel.stacksize) {
// System.err.println("ILGenerator.Emit: Stack depth differs depending on path:");
// System.err.println("\tmethod = " + owner);
// System.err.println("\tPC = 0x" + Table.short2hex(lastLabel.address));
// }
//assert arg.stacksize == lastLabel.stacksize;
}
else {
label.setStacksize(lastLabel.getStacksize())
}
}
/**
* Puts the specified instruction onto the Microsoft intermediate
* language (MSIL) stream and leaves space to include a label when
* fixes are done.
*/
def Emit(opcode: OpCode, arg: Array[Label] ) {
assert(arg != null)
// switch
// <instr> ::= <instr_switch> ( <labels> )
// Examples:
// switch (0x3, -14, Label1)
// switch (5, Label2)
emit(opcode, arg, arg.length)
}
/**
* Puts the specified instruction onto the Microsoft intermediate
* language (MSIL) stream followed by the metadata token for the
* given method.
*/
def Emit(opcode: OpCode,arg: MethodInfo) {
assert(arg != null)
// call | callvirt | jmp | ldftn | ldvirtftn
// pop size is the number of parameters
// pop 1 more if method is not static !
// push size is either 0 (void Method) either 1
assert(arg.ReturnType != null, "No ReturnType: " + arg.DeclaringType + "::" + arg.Name)
val popush: Int = if (opcode == OpCode.Ldftn ||
opcode == OpCode.Ldvirtftn ||
opcode == OpCode.Jmp)
{
OpCode.PUSH_size(opcode.CEE_push) - OpCode.POP_size(opcode.CEE_pop)
} else if (opcode == OpCode.Calli || opcode == OpCode.Callvirt) {
(if(arg.ReturnType == VOID) 0 else 1) - arg.GetParameters().length - 1
} else {
(if(arg.ReturnType == VOID) 0 else 1) - arg.GetParameters().length
}
emit(opcode, arg, popush)
}
/**
* Puts the specified instruction and numerical argument onto
* the Microsoft intermediate language (MSIL) stream of instructions.
*/
def Emit(opcode: OpCode, arg: Float ) {
emit(opcode, new java.lang.Float(arg))
}
/**
* Puts the specified instruction onto the Microsoft intermediate
* language (MSIL) stream followed by the metadata token for the
* given string.
*/
def Emit(opcode: OpCode, arg: String ) {
assert(arg != null)
// ldstr
emit(opcode, arg)
}
/**
* Puts the specified instruction onto the Microsoft intermediate
* language (MSIL) stream followed by the metadata token for the
* given type.
*/
def Emit(opcode: OpCode, arg: Type) {
assert(arg != null)
// box | castclass | cpobj | initobj | isinst |
// ldelema | ldobj | mkrefany | newarr | refanyval |
// sizeof | stobj | unbox
emit(opcode, arg)
}
/**
* Puts a call or callvirt instruction onto the Microsoft intermediate
* language (MSIL) stream.
*/
def EmitCall(opcode: OpCode, arg: MethodInfo,
optionalParameterTypes: Array[Type]) {
assert(arg != null)
// pop size is the number of parameters
// push size is either 0 (void Method) either 1
//System.out.println(arg.ReturnType.Size + " " + arg.GetParameters().length);
emit(opcode, arg, (if(arg.ReturnType == VOID) 0 else 1) -
arg.GetParameters().length)
}
/**
* Emits the Microsoft intermediate language (MSIL) necessary to
* call WriteLine with the given field.
*/
def EmitWriteLine(arg: FieldInfo) {
// first load field info
// if static use OpCode.Ldsfld
if (arg.IsStatic())
Emit(OpCodes.Ldsfld, arg)
else
Emit(OpCodes.Ldfld, arg)
// then call System.Console.WriteLine(arg.Type)
val t: Type = Type.GetType("System.Console")
val argsType: Array[Type] = new Array[Type](1)
argsType(0) = arg.FieldType
val m: MethodInfo = t.GetMethod("WriteLine", argsType)
EmitCall(OpCode.Call, m, null)
}
/**
* Emits the Microsoft intermediate language (MSIL) necessary
* to call WriteLine with the given local variable.
*/
def EmitWriteLine(arg: LocalBuilder) {
// first load local variable
Emit(OpCodes.Ldloc, arg)
// then call System.Console.WriteLine(arg.Type)
val t: Type = Type.GetType("System.Console")
val argsType: Array[Type] = new Array[Type](1)
argsType(0) = arg.LocalType
val m: MethodInfo = t.GetMethod("WriteLine", argsType)
EmitCall(OpCode.Call, m, null)
}
/**
* Emits the Microsoft intermediate language (MSIL) to call
* WriteLine with a string.
*/
def EmitWriteLine(arg: String) {
// first load string
Emit(OpCode.Ldstr, arg)
// then call System.Console.WriteLine(string)
val t: Type = Type.GetType("System.Console")
val argsType: Array[Type] = new Array[Type](1)
argsType(0) = Type.GetType("System.String")
val m: MethodInfo = t.GetMethod("WriteLine", argsType)
EmitCall(OpCode.Call, m, null)
}
/**
* Declares a local variable.
*/
def DeclareLocal(localType: Type): LocalBuilder = {
val l: LocalBuilder = new LocalBuilder(locals, localType)
locals = locals + 1
localList.add(l)
return l
}
/**
* Returns a new label that can be used as a token for branching.
* In order to set the position of the label within the stream, you
* must call MarkLabel. This is just a token and does not yet represent
* any particular location within the stream.
*/
def DefineLabel():Label = {
new Label.NormalLabel()
}
/**
* Marks the Microsoft intermediate language (MSIL) stream's
* current position with the given label.
*/
def MarkLabel(label: Label) {
label.mergeWith(lastLabel)
/*
label.address = lastLabel.address;
//label.stacksize = lastLabel.stacksize;
if (label.stacksize >= 0)
lastLabel.stacksize = label.stacksize;
*/
}
/** Begins a lexical scope. */
def BeginScope() {
emitSpecialLabel(Label.NewScope)
}
/** Ends a lexical scope. */
def EndScope() {
emitSpecialLabel(Label.EndScope)
}
/**
* Begins an exception block for a non-filtered exception.
* The label for the end of the block. This will leave you in the correct
* place to execute finally blocks or to finish the try.
*/
def BeginExceptionBlock() {
emitSpecialLabel(Label.Try)
val endExc: Label = new Label.NormalLabel() // new Label(lastLabel) ???
excStack.push(Label.Try, endExc)
return endExc
}
/** Begins a catch block. */
def BeginCatchBlock(exceptionType: Type) {
val kind = excStack.peekKind()
if (kind == Label.Kind.Try ||
kind == Label.Kind.Catch) {
/* ok */
} else {
throw new RuntimeException("Catch should follow either a try or catch")
}
val endExc: Label = excStack.popLabel()
Emit(OpCodes.Leave, endExc)
// the CLI automatically provide the exception object on the evaluation stack
// we adjust the stacksize
lastLabel.incStacksize()
excStack.push(Label.Catch, endExc)
emitSpecialLabel(Label.Catch, exceptionType)
}
/** Ends an exception block. */
def EndExceptionBlock() {
val kind = excStack.peekKind()
if (kind == Label.Kind.Try) {
throw new RuntimeException("Try block with neither catch nor finally")
} else if (kind == Label.Kind.Catch) {
Emit(OpCodes.Leave, excStack.peekLabel())
} else if (kind == Label.Kind.Finally) {
Emit(OpCodes.Endfinally)
}
MarkLabel(excStack.popLabel())
emitSpecialLabel(Label.EndTry)
}
/**
* Begins a finally block in the Microsoft intermediate language
* (MSIL) instruction stream.
*/
def BeginFinallyBlock() {
val endExc: Label = excStack.popLabel()
Emit(OpCodes.Leave, endExc)
excStack.push(Label.Finally, endExc)
emitSpecialLabel(Label.Finally)
}
/**
* Emits an instruction to throw an exception.
*/
def ThrowException(exceptionType: Type) {
assert(exceptionType != null)
if (!exceptionType.isSubtypeOf(Type.GetType("System.Exception")))
throw new RuntimeException
(exceptionType + " doesn't extend System.Exception" )
val ctor: ConstructorInfo = exceptionType.GetConstructor(Type.EmptyTypes)
if (ctor == null)
throw new RuntimeException("Type " + exceptionType
+ "doesn't have a default constructor")
Emit(OpCodes.Newobj, ctor)
Emit(OpCodes.Throw)
}
/**
* sets the line of the source file corresponding to the next instruction
*/
def setPosition(line: Int) {
if (line != 0)
lineNums.put(lastLabel, Integer.toString(line))
}
def setPosition(line: Int, filename: String) {
if (line != 0)
lineNums.put(lastLabel, line + " '" + filename + "'")
}
def getLocals(): Array[LocalBuilder] = {
localList.toArray(new Array[LocalBuilder](0)).asInstanceOf[Array[LocalBuilder]]
}
def getLabelIterator(): Iterator[Label] = {
labelList.iterator()
}
def getOpcodeIterator(): Iterator[OpCode] = {
opcodeList.iterator()
}
def getArgumentIterator(): Iterator[Object] = {
argumentList.iterator()
}
//##########################################################################
// private implementation details
// the local variable list
private final val localList: ArrayList[LocalBuilder] = new ArrayList[LocalBuilder]()
// the label list, the opcode list and the opcode argument list
// labelList is an array of Label
// opcodeList is an array of OpCode
// argumentList is an array of Object (null if no argument)
private final val labelList: ArrayList[Label] = new ArrayList[Label]()
private final val opcodeList: ArrayList[OpCode] = new ArrayList[OpCode]()
private final val argumentList: ArrayList[Object] = new ArrayList[Object]()
// the program counter (pc)
// also called the stream's current position
private var pc: Int = 0
// last label
private var lastLabel: Label = new Label.NormalLabel(pc,0)
// the maximum size of stack
private var maxstack: Int = 0
// the number of the locals
private var locals: Int = 0
// stack of label for exception mechanism
private var excStack: ExceptionStack = new ExceptionStack()
// the method info owner of this ILGenerator
var owner: MethodBase = _owner
val lineNums: Map[Label, String] = new HashMap[Label, String]()
def getMaxStacksize(): Int = { this.maxstack }
// private emit with Object Argument
private def emit(opcode: OpCode, arg: Object) {
emit(opcode, arg, opcode.CEE_popush)
}
// private emit with Object Argument and override POPUSH
private def emit(opcode: OpCode, arg: Object, overridePOPUSH: Int) {
// add label, opcode and argument
labelList.add(lastLabel)
opcodeList.add(opcode)
argumentList.add(arg)
// compute new lastLabel (next label)
val stackSize: Int = lastLabel.getStacksize() + overridePOPUSH
if (stackSize < 0) {
throw new RuntimeException("ILGenerator.emit(): Stack underflow in method: " + owner)
}
if (stackSize > maxstack)
maxstack = stackSize
var address: Int = lastLabel.getAddress() + opcode.CEE_length
if (opcode.CEE_opcode == OpCode.CEE_SWITCH) {
address = address + 4*arg.asInstanceOf[Array[Label]].length
}
lastLabel = new Label.NormalLabel(address, stackSize)
pc = pc + 1
}
private def emitSpecialLabel(l: Label) {
emitSpecialLabel(l, null)
}
private def emitSpecialLabel(l: Label, catchType: Type) {
labelList.add(l)
opcodeList.add(null)
argumentList.add(catchType)
}
//##########################################################################
//
@throws(classOf[IOException])
def apply(v: Visitor) {
v.caseILGenerator(this)
}
//##########################################################################
} // class ILGenerator
object ILGenerator {
val VOID: Type = Type.GetType("System.Void")
val NO_LABEL: String = ""
private final class ExceptionStack {
private val labels: Stack[Label] = new Stack[Label]()
private val kinds: Stack[Label] = new Stack[Label]()
def ExceptionStack() {}
def pop() { labels.pop(); kinds.pop() }
def push(kind: Label, label: Label) {
kinds.push(kind); labels.push(label)
}
def peekKind(): Label.Kind = {kinds.peek().asInstanceOf[Label].getKind() }
def peekLabel(): Label = { labels.peek().asInstanceOf[Label] }
def popLabel(): Label = { kinds.pop(); labels.pop().asInstanceOf[Label]}
}
}
|