-
Notifications
You must be signed in to change notification settings - Fork 541
/
Copy pathLlvmIrInstructions.cs
627 lines (531 loc) · 18.7 KB
/
LlvmIrInstructions.cs
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Xamarin.Android.Tasks.LLVMIR;
abstract class LlvmIrInstruction : LlvmIrFunctionBodyItem
{
public string Mnemonic { get; }
public LlvmIrFunctionAttributeSet? AttributeSet { get; set; }
/// <summary>
/// TBAA (Type Based Alias Analysis) metadata item the instruction references, if any.
/// <see cref="LlvmIrModule.TbaaAnyPointer"/> for more information about TBAA.
/// </summary>
public LlvmIrMetadataItem? TBAA { get; set; }
protected LlvmIrInstruction (string mnemonic)
{
if (String.IsNullOrEmpty (mnemonic)) {
throw new ArgumentException ("must not be null or empty", nameof (mnemonic));
}
Mnemonic = mnemonic;
}
protected override void DoWrite (GeneratorWriteContext context, LlvmIrGenerator generator)
{
context.Output.Write (context.CurrentIndent);
WriteValueAssignment (context);
WritePreamble (context);
context.Output.Write (Mnemonic);
context.Output.Write (' ');
WriteBody (context);
if (TBAA != null) {
context.Output.Write (", !tbaa !");
context.Output.Write (TBAA.Name);
}
if (AttributeSet != null) {
context.Output.Write (" #");
context.Output.Write (AttributeSet.Number.ToString (CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Write the '<variable_reference> = ' part of the instruction line.
/// </summary>
protected virtual void WriteValueAssignment (GeneratorWriteContext context)
{}
/// <summary>
/// Write part of the instruction that comes between the optional value assignment and the instruction
/// mnemonic. If any text is written, it must end with a whitespace.
/// </summary>
protected virtual void WritePreamble (GeneratorWriteContext context)
{}
/// <summary>
/// Write the "body" of the instruction, that is the part that follows instruction mnemonic but precedes the
/// metadata and attribute set references.
/// </summary>
protected virtual void WriteBody (GeneratorWriteContext context)
{}
protected void WriteValue (GeneratorWriteContext context, Type type, object? value, bool isPointer)
{
if (value == null) {
if (!isPointer) {
throw new InvalidOperationException ($"Internal error: non-pointer type '{type}' must not have a `null` value");
}
context.Output.Write ("null");
} else if (value is LlvmIrVariable variable) {
context.Output.Write (variable.Reference);
} else {
context.Output.Write (MonoAndroidHelper.CultureInvariantToString (value));
}
}
protected void WriteAlignment (GeneratorWriteContext context, ulong typeSize, bool isPointer)
{
context.Output.Write (", align ");
ulong alignment;
if (isPointer) {
alignment = context.Target.NativePointerSize;
} else {
alignment = typeSize;
}
context.Output.Write (alignment.ToString (CultureInfo.InvariantCulture));
}
}
abstract class LlvmIrInstructionArgumentValuePlaceholder
{
protected LlvmIrInstructionArgumentValuePlaceholder ()
{}
public abstract object? GetValue (LlvmIrModuleTarget target);
}
class LlvmIrInstructionPointerSizeArgumentPlaceholder : LlvmIrInstructionArgumentValuePlaceholder
{
public override object? GetValue (LlvmIrModuleTarget target)
{
return target.NativePointerSize;
}
}
sealed class LlvmIrInstructions
{
public class Alloca : LlvmIrInstruction
{
LlvmIrVariable result;
public Alloca (LlvmIrVariable result)
: base ("alloca")
{
this.result = result;
}
protected override void WriteValueAssignment (GeneratorWriteContext context)
{
if (result == null) {
return;
}
context.Output.Write (result.Reference);
context.Output.Write (" = ");
}
protected override void WriteBody (GeneratorWriteContext context)
{
string irType = LlvmIrGenerator.MapToIRType (result.Type, context.TypeCache, out ulong size, out bool isPointer);
context.Output.Write (irType);
WriteAlignment (context, size, isPointer);
}
}
public class Br : LlvmIrInstruction
{
const string OpName = "br";
LlvmIrVariable? cond;
LlvmIrFunctionLabelItem ifTrue;
LlvmIrFunctionLabelItem? ifFalse;
/// <summary>
/// Outputs a conditional branch to label <paramref name="ifTrue"/> if condition <paramref name="cond"/> is
/// <c>true</c>, and to label <paramref name="ifFalse"/> otherwise. <paramref name="cond"/> must be a variable
/// of type <c>bool</c>
/// </summary>
public Br (LlvmIrVariable cond, LlvmIrFunctionLabelItem ifTrue, LlvmIrFunctionLabelItem ifFalse)
: base (OpName)
{
if (cond.Type != typeof(bool)) {
throw new ArgumentException ($"Internal error: condition must refer to a variable of type 'bool', was 'cond.Type' instead", nameof (cond));
}
this.cond = cond;
this.ifTrue = ifTrue;
this.ifFalse = ifFalse;
}
/// <summary>
/// Outputs an unconditional branch to label <paramref name="label"/>
/// </summary>
public Br (LlvmIrFunctionLabelItem label)
: base (OpName)
{
ifTrue = label;
}
protected override void WriteBody (GeneratorWriteContext context)
{
if (cond == null) {
context.Output.Write ("label %");
context.Output.Write (ifTrue.Name);
return;
}
context.Output.Write ("i1 ");
context.Output.Write (cond.Reference);
context.Output.Write (", label %");
context.Output.Write (ifTrue.Name);
context.Output.Write (", label %");
context.Output.Write (ifFalse.Name);
}
}
public class Call : LlvmIrInstruction
{
LlvmIrFunction function;
IList<object?>? arguments;
LlvmIrVariable? result;
public LlvmIrCallMarker CallMarker { get; set; } = LlvmIrCallMarker.None;
/// <summary>
/// This needs to be set if we want to call a function via a local or global variable. <see cref="LlvmIrFunction"/> passed
/// to the constructor is then used only to generate a type safe call, while function address comes from the variable assigned
/// to this property.
/// </summary>
public LlvmIrVariable? FuncPointer { get; set; }
public Call (LlvmIrFunction function, LlvmIrVariable? result = null, ICollection<object?>? arguments = null, LlvmIrVariable? funcPointer = null)
: base ("call")
{
this.function = function;
this.result = result;
this.FuncPointer = funcPointer;
if (function.Signature.ReturnType != typeof(void)) {
if (result == null) {
throw new ArgumentNullException ($"Internal error: function '{function.Signature.Name}' returns '{function.Signature.ReturnType} and thus requires a result variable", nameof (result));
}
} else if (result != null) {
throw new ArgumentException ($"Internal error: function '{function.Signature.Name}' returns no value and yet a result variable was provided", nameof (result));
}
int argCount = function.Signature.Parameters.Count;
if (argCount != 0) {
if (arguments == null) {
throw new ArgumentNullException ($"Internal error: function '{function.Signature.Name}' requires {argCount} arguments", nameof (arguments));
}
if (function.UsesVarArgs) {
if (arguments.Count < argCount) {
throw new ArgumentException ($"Internal error: varargs function '{function.Signature.Name}' needs at least {argCount} fixed arguments, got {arguments.Count} instead");
}
} else if (arguments.Count != argCount) {
throw new ArgumentException ($"Internal error: function '{function.Signature.Name}' requires {argCount} arguments, but {arguments.Count} were provided", nameof (arguments));
}
this.arguments = new List<object> (arguments).AsReadOnly ();
}
}
protected override void WriteValueAssignment (GeneratorWriteContext context)
{
if (result == null) {
return;
}
context.Output.Write (result.Reference);
context.Output.Write (" = ");
}
protected override void WritePreamble (GeneratorWriteContext context)
{
string? callMarker = CallMarker switch {
LlvmIrCallMarker.None => null,
LlvmIrCallMarker.Tail => "tail",
LlvmIrCallMarker.NoTail => "notail",
LlvmIrCallMarker.MustTail => "musttail",
_ => throw new InvalidOperationException ($"Internal error: call marker '{CallMarker}' not supported"),
};
if (!String.IsNullOrEmpty (callMarker)) {
context.Output.Write (callMarker);
context.Output.Write (' ');
}
}
protected override void WriteBody (GeneratorWriteContext context)
{
if (function.ReturnsValue) {
LlvmIrGenerator.WriteReturnAttributes (context, function.Signature.ReturnAttributes);
}
context.Output.Write (LlvmIrGenerator.MapToIRType (function.Signature.ReturnType, context.TypeCache));
if (function.UsesVarArgs) {
context.Output.Write (" (");
for (int j = 0; j < function.Signature.Parameters.Count; j++) {
if (j > 0) {
context.Output.Write (", ");
}
LlvmIrFunctionParameter parameter = function.Signature.Parameters[j];
string irType = parameter.IsVarArgs ? "..." : LlvmIrGenerator.MapToIRType (parameter.Type, context.TypeCache);
context.Output.Write (irType);
}
context.Output.Write (')');
}
if (FuncPointer == null) {
context.Output.Write (" @");
context.Output.Write (function.Signature.Name);
} else {
context.Output.Write (' ');
context.Output.Write (FuncPointer.Reference);
}
context.Output.Write ('(');
bool isVararg = false;
int i;
for (i = 0; i < function.Signature.Parameters.Count; i++) {
if (i > 0) {
context.Output.Write (", ");
}
LlvmIrFunctionParameter parameter = function.Signature.Parameters[i];
if (parameter.IsVarArgs) {
isVararg = true;
}
WriteArgument (context, parameter, i, isVararg);
}
if (arguments != null) {
for (; i < arguments.Count; i++) {
context.Output.Write (", ");
WriteArgument (context, null, i, isVararg: true);
}
}
context.Output.Write (')');
}
void WriteArgument (GeneratorWriteContext context, LlvmIrFunctionParameter? parameter, int index, bool isVararg)
{
object? value = arguments[index];
if (value is LlvmIrInstructionArgumentValuePlaceholder placeholder) {
value = placeholder.GetValue (context.Target);
}
string irType;
if (!isVararg) {
irType = LlvmIrGenerator.MapToIRType (parameter.Type, context.TypeCache);
} else if (value is LlvmIrVariable v1) {
irType = LlvmIrGenerator.MapToIRType (v1.Type, context.TypeCache);
} else {
if (value == null) {
// We have no way of verifying the vararg parameter type if value is null, so we'll assume it's a pointer.
// If our assumption is wrong, llc will fail and signal the error
irType = "ptr";
} else {
irType = LlvmIrGenerator.MapToIRType (value.GetType (), context.TypeCache);
}
}
context.Output.Write (irType);
if (parameter != null) {
LlvmIrGenerator.WriteParameterAttributes (context, parameter);
}
context.Output.Write (' ');
if (value == null) {
if (!parameter.Type.IsNativePointer (context.TypeCache)) {
throw new InvalidOperationException ($"Internal error: value for argument {index} to function '{function.Signature.Name}' must not be null");
}
context.Output.Write ("null");
return;
}
if (value is LlvmIrVariable v2) {
context.Output.Write (v2.Reference);
return;
}
if (parameter != null && !parameter.Type.IsAssignableFrom (value.GetType ())) {
throw new InvalidOperationException ($"Internal error: value type '{value.GetType ()}' for argument {index} to function '{function.Signature.Name}' is invalid. Expected '{parameter.Type}' or compatible");
}
if (value is string || value is StringHolder) {
context.Output.Write (context.Module.LookupRequiredVariableForString (StringHolder.AsHolder (value)).Reference);
return;
}
if (LlvmIrGenerator.IsFirstClassNonPointerType (value.GetType ())) {
context.Output.Write (MonoAndroidHelper.CultureInvariantToString (value));
return;
}
throw new InvalidOperationException ($"Internal error: unsupported type '{value.GetType ()}' in call to function '{function.Signature.Name}'");
}
}
public class Ext : LlvmIrInstruction
{
const string FpextOpCode = "fpext";
const string SextOpCode = "sext";
const string ZextOpCode = "zext";
LlvmIrVariable result;
LlvmIrVariable source;
Type targetType;
public Ext (LlvmIrVariable source, Type targetType, LlvmIrVariable result)
: base (GetOpCode (targetType))
{
this.source = source;
this.targetType = targetType;
this.result = result;
}
protected override void WriteValueAssignment (GeneratorWriteContext context)
{
context.Output.Write (result.Reference);
context.Output.Write (" = ");
}
protected override void WriteBody (GeneratorWriteContext context)
{
context.Output.Write (LlvmIrGenerator.MapToIRType (source.Type, context.TypeCache));
context.Output.Write (' ');
context.Output.Write (source.Reference);
context.Output.Write (" to ");
context.Output.Write ( LlvmIrGenerator.MapToIRType (targetType, context.TypeCache));
}
static string GetOpCode (Type targetType)
{
if (targetType == typeof(double)) {
return FpextOpCode;
} else if (targetType == typeof(int)) {
return SextOpCode;
} else if (targetType == typeof(uint)) {
return ZextOpCode;
} else {
throw new InvalidOperationException ($"Unsupported target type for upcasting: {targetType}");
}
}
}
public class Icmp : LlvmIrInstruction
{
LlvmIrIcmpCond cond;
LlvmIrVariable op1;
object? op2;
LlvmIrVariable result;
public Icmp (LlvmIrIcmpCond cond, LlvmIrVariable op1, object? op2, LlvmIrVariable result)
: base ("icmp")
{
if (result.Type != typeof(bool)) {
throw new ArgumentException ($"Internal error: result must be a variable of type 'bool', was '{result.Type}' instead", nameof (result));
}
this.cond = cond;
this.op1 = op1;
this.op2 = op2;
this.result = result;
}
protected override void WriteValueAssignment (GeneratorWriteContext context)
{
context.Output.Write (result.Reference);
context.Output.Write (" = ");
}
protected override void WriteBody (GeneratorWriteContext context)
{
string irType = LlvmIrGenerator.MapToIRType (op1.Type, context.TypeCache, out ulong size, out bool isPointer);
string condOp = cond switch {
LlvmIrIcmpCond.Equal => "eq",
LlvmIrIcmpCond.NotEqual => "ne",
LlvmIrIcmpCond.UnsignedGreaterThan => "ugt",
LlvmIrIcmpCond.UnsignedGreaterOrEqual => "uge",
LlvmIrIcmpCond.UnsignedLessThan => "ult",
LlvmIrIcmpCond.UnsignedLessOrEqual => "ule",
LlvmIrIcmpCond.SignedGreaterThan => "sgt",
LlvmIrIcmpCond.SignedGreaterOrEqual => "sge",
LlvmIrIcmpCond.SignedLessThan => "slt",
LlvmIrIcmpCond.SignedLessOrEqual => "sle",
_ => throw new InvalidOperationException ($"Unsupported `icmp` conditional '{cond}'"),
};
context.Output.Write (condOp);
context.Output.Write (' ');
context.Output.Write (irType);
context.Output.Write (' ');
context.Output.Write (op1.Reference);
context.Output.Write (", ");
WriteValue (context, op1.Type, op2, isPointer);
}
}
public class Load : LlvmIrInstruction
{
LlvmIrVariable source;
LlvmIrVariable result;
public Load (LlvmIrVariable source, LlvmIrVariable result)
: base ("load")
{
this.source = source;
this.result = result;
}
protected override void WriteValueAssignment (GeneratorWriteContext context)
{
context.Output.Write (result.Reference);
context.Output.Write (" = ");
}
protected override void WriteBody (GeneratorWriteContext context)
{
string irType = LlvmIrGenerator.MapToIRType (result.Type, context.TypeCache, out ulong size, out bool isPointer);
context.Output.Write (irType);
context.Output.Write (", ptr ");
WriteValue (context, result.Type, source, isPointer);
WriteAlignment (context, size, isPointer);
}
}
public class Phi : LlvmIrInstruction
{
LlvmIrVariable result;
LlvmIrVariable val1;
LlvmIrFunctionLabelItem label1;
LlvmIrVariable val2;
LlvmIrFunctionLabelItem label2;
/// <summary>
/// Represents the `phi` instruction form we use the most throughout marshal methods generator - one which refers to an if/else block and where
/// **both** value:label pairs are **required**. Parameters <paramref name="label1"/> and <paramref name="label2"/> are nullable because, in theory,
/// it is possible that <see cref="LlvmIrFunctionBody"/> hasn't had the required blocks defined prior to adding the `phi` instruction and, thus,
/// we must check for the possibility here.
/// </summary>
public Phi (LlvmIrVariable result, LlvmIrVariable val1, LlvmIrFunctionLabelItem? label1, LlvmIrVariable val2, LlvmIrFunctionLabelItem? label2)
: base ("phi")
{
this.result = result;
this.val1 = val1;
this.label1 = label1 ?? throw new ArgumentNullException (nameof (label1));
this.val2 = val2;
this.label2 = label2 ?? throw new ArgumentNullException (nameof (label2));
}
protected override void WriteValueAssignment (GeneratorWriteContext context)
{
context.Output.Write (result.Reference);
context.Output.Write (" = ");
}
protected override void WriteBody (GeneratorWriteContext context)
{
context.Output.Write (LlvmIrGenerator.MapToIRType (result.Type, context.TypeCache));
context.Output.Write (" [");
context.Output.Write (val1.Reference);
context.Output.Write (", %");
context.Output.Write (label1.Name);
context.Output.Write ("], [");
context.Output.Write (val2.Reference);
context.Output.Write (", %");
context.Output.Write (label2.Name);
context.Output.Write (']');
}
}
public class Ret : LlvmIrInstruction
{
Type retvalType;
object? retVal;
public Ret (Type retvalType, object? retval = null)
: base ("ret")
{
this.retvalType = retvalType;
retVal = retval;
}
protected override void WriteBody (GeneratorWriteContext context)
{
if (retvalType == typeof(void)) {
context.Output.Write ("void");
return;
}
string irType = LlvmIrGenerator.MapToIRType (retvalType, context.TypeCache, out bool isPointer);
context.Output.Write (irType);
context.Output.Write (' ');
WriteValue (context, retvalType, retVal, isPointer);
}
}
public class Store : LlvmIrInstruction
{
const string Opcode = "store";
object? from;
LlvmIrVariable to;
public Store (LlvmIrVariable from, LlvmIrVariable to)
: base (Opcode)
{
this.from = from;
this.to = to;
}
/// <summary>
/// Stores `null` in the indicated variable
/// </summary>
public Store (LlvmIrVariable to)
: base (Opcode)
{
this.to = to;
}
protected override void WriteBody (GeneratorWriteContext context)
{
string irType = LlvmIrGenerator.MapToIRType (to.Type, context.TypeCache, out ulong size, out bool isPointer);
context.Output.Write (irType);
context.Output.Write (' ');
WriteValue (context, to.Type, from, isPointer);
context.Output.Write (", ptr ");
context.Output.Write (to.Reference);
WriteAlignment (context, size, isPointer);
}
}
public class Unreachable : LlvmIrInstruction
{
public Unreachable ()
: base ("unreachable")
{}
}
}