Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EvaluationStack.cs « CodeGen « src « ILCompiler.WebAssembly « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 92c191976424a2daed4a5dd28044e7fb4544aa2f (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics;
using System.Text;
using ILCompiler.Compiler.CppCodeGen;
using Internal.TypeSystem;
using LLVMSharp;
using ILCompiler.CodeGen;
using System.Collections.Generic;

namespace Internal.IL
{
    /// <summary>
    /// Abstraction of a variable size last-in-first-out (LIFO) collection of instances of the same specified type
    /// implemented via an array.
    /// </summary>
    /// <typeparam name="T">Type of elements in the stack.</typeparam>
    internal class EvaluationStack<T>
    {
        /// <summary>
        /// Initializes a new instance of the stack that is empty and has the specified initial capacity <paramref name="n"/>.
        /// </summary>
        /// <param name="n">Initial number of elements that the stack can contain.</param>
        public EvaluationStack(int n)
        {
            Debug.Assert(n >= 0, "Count should be non-negative");

            _stack = n > 0 ? new T[n] : s_emptyStack;
            _top = 0;

            Debug.Assert(n == _stack.Length, "Stack length does not match requested capacity");
            Debug.Assert(_top == 0, "Top of stack is at bottom");
        }

        /// <summary>
        /// Value for all stacks of length 0.
        /// </summary>
        private static readonly T[] s_emptyStack = new T[0];

        /// <summary>
        /// Storage for current stack.
        /// </summary>
        private T[] _stack;

        /// <summary>
        /// Position in <see cref="_stack"/> where next element will be pushed.
        /// </summary>
        private int _top;

        /// <summary>
        /// Position in stack where next element will be pushed.
        /// </summary>
        public int Top
        {
            get { return _top; }
        }

        /// <summary>
        /// Number of elements contained in the stack.
        /// </summary>
        public int Length
        {
            get { return _top; }
        }

        /// <summary>
        /// Push <paramref name="value"/> at the top of the stack.
        /// </summary>
        /// <param name="value">Element to push onto the stack.</param>
        public void Push(T value)
        {
            if (_top >= _stack.Length)
            {
                Array.Resize(ref _stack, 2 * _top + 3);
            }
            _stack[_top++] = value;
        }

        /// <summary>
        /// Insert <paramref name="v"/> at position <paramref name="pos"/> in current stack, shifting all
        /// elements after or at <paramref name="pos"/> by one.
        /// </summary>
        /// <param name="v">Element to insert</param>
        /// <param name="pos">Position where to insert <paramref name="v"/></param>
        public void InsertAt(T v, int pos)
        {
            Debug.Assert(pos <= _top, "Invalid insertion point");

            if (_top >= _stack.Length)
            {
                Array.Resize(ref _stack, 2 * _top + 3);
            }
            for (int i = _top - 1; i >= pos; i--)
            {
                _stack[i + 1] = _stack[i];
            }
            _top++;
            _stack[pos] = v;
        }

        /// <summary>
        /// Access and set 
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public T this[int index]
        {
            get
            {
                Debug.Assert(index >= 0 && index < _top, "Index not in range");
                return _stack[index];
            }
            set
            {
                Debug.Assert(index >= 0 && index < _top, "Index not in range");
                _stack[index] = value;
            }
        }

        /// <summary>
        /// Return element of the top of the stack.
        /// </summary>
        /// <returns>Element at the top of the stack</returns>
        public T Peek()
        {
            if (_top <= 0)
            {
                ThrowHelper.ThrowInvalidProgramException();
            }

            return _stack[_top - 1];
        }

        /// <summary>
        /// Remove top element from stack and return it.
        /// </summary>
        /// <returns>Element formerly at the top of the stack</returns>
        public T Pop()
        {
            if (_top <= 0)
            {
                ThrowHelper.ThrowInvalidProgramException();
            }

            return _stack[--_top];
        }

        /// <summary>
        /// Remove <paramref name="n"/> elements from the stack.
        /// </summary>
        /// <param name="n">Number of elements to remove from the stack</param>
        public void PopN(int n)
        {
            Debug.Assert(n <= _top, "Too many elements to remove");
            _top -= n;
        }

        /// <summary>
        /// Remove all elements from the stack.
        /// </summary>
        public void Clear()
        {
            _top = 0;
        }
    }

    /// <summary>
    /// Abstract representation of a stack entry
    /// </summary>
    internal abstract class StackEntry
    {
        /// <summary>
        /// Evaluation stack kind of the entry. 
        /// </summary>
        public StackValueKind Kind { get; }

        /// <summary>
        /// Managed type if any of the entry.
        /// </summary>
        public TypeDesc Type { get; }

        public LLVMValueRef ValueAsType(LLVMTypeRef type, LLVMBuilderRef builder)
        {
            return ValueAsTypeInternal(type, builder, false);
        }

        public LLVMValueRef ValueAsType(TypeDesc type, LLVMBuilderRef builder)
        {
            return ValueAsType(ILImporter.GetLLVMTypeForTypeDesc(type), builder);
        }

        public LLVMValueRef ValueForStackKind(StackValueKind kind, LLVMBuilderRef builder, bool signExtend)
        {
            if (kind == StackValueKind.Int32)
                return ValueAsInt32(builder, signExtend);
            else if (kind == StackValueKind.Int64)
                return ValueAsInt64(builder, signExtend);
            else if (kind == StackValueKind.Float)
                return ValueAsType(LLVM.FloatType(), builder);
            else if (kind == StackValueKind.NativeInt || kind == StackValueKind.ByRef || kind == StackValueKind.ObjRef)
                return ValueAsInt32(builder, false);
            else
                throw new NotImplementedException();
        }

        public LLVMValueRef ValueAsInt32(LLVMBuilderRef builder, bool signExtend)
        {
            return ValueAsTypeInternal(LLVM.Int32Type(), builder, signExtend);
        }

        public LLVMValueRef ValueAsInt64(LLVMBuilderRef builder, bool signExtend)
        {
            return ValueAsTypeInternal(LLVM.Int32Type(), builder, signExtend);
        }

        protected abstract LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend);

        /// <summary>
        /// Initializes a new instance of StackEntry.
        /// </summary>
        /// <param name="kind">Kind of entry.</param>
        /// <param name="type">Type if any of entry.</param>
        protected StackEntry(StackValueKind kind, TypeDesc type = null)
        {
            Kind = kind;
            Type = type;
        }

        /// <summary>
        /// Add representation of current entry in <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">Generation buffer used for appending new content.</param>
        //public abstract void Append(CppGenerationBuffer builder);

        /// <summary>
        /// Create a new copy of current entry.
        /// </summary>
        /// <returns>A new instance of the same type as the current entry.</returns>
        public abstract StackEntry Duplicate();
    }

    /// <summary>
    /// Abstract entry for all constant values.
    /// </summary>
    internal abstract class ConstantEntry : StackEntry
    {
        protected ConstantEntry(StackValueKind kind, TypeDesc type = null) : base(kind, type)
        {
        }

        /// <summary>
        /// Does current entry require a cast to be assigned to <paramref name="destType"/>?
        /// </summary>
        /// <param name="destType">Type of destination</param>
        /// <returns>True if a cast is required</returns>
        public virtual bool IsCastNecessary(TypeDesc destType)
        {
            return false;
        }
    }

    internal abstract class ConstantEntry<T> : ConstantEntry where T : IConvertible
    {
        public T Value { get; }

        protected ConstantEntry(StackValueKind kind, T value, TypeDesc type = null) : base(kind, type)
        {
            Value = value;
        }
    }

    internal class Int32ConstantEntry : ConstantEntry<int>
    {
        public Int32ConstantEntry(int value, TypeDesc type = null) : base(StackValueKind.Int32, value, type)
        {
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            if (type.TypeKind == LLVMTypeKind.LLVMPointerTypeKind && Value == 0)
            {
                return LLVM.ConstPointerNull(type);
            }
            else if (type.TypeKind == LLVMTypeKind.LLVMPointerTypeKind && Value != 0)
            {
                return LLVM.ConstIntToPtr(LLVM.ConstInt(LLVM.Int32Type(), (ulong)Value, LLVMMisc.False), type);
            }
            else if (type.TypeKind != LLVMTypeKind.LLVMIntegerTypeKind)
            {
                throw new NotImplementedException();
            }
            else
            {
                return LLVM.ConstInt(type, (ulong)Value, LLVMMisc.False);
            }
        }

        public override StackEntry Duplicate()
        {
            return new Int32ConstantEntry(Value, Type);
        }

        public override bool IsCastNecessary(TypeDesc destType)
        {
            switch (destType.UnderlyingType.Category)
            {
                case TypeFlags.SByte:
                    return Value >= sbyte.MaxValue || Value <= sbyte.MinValue;
                case TypeFlags.Byte:
                case TypeFlags.Boolean:
                    return Value >= byte.MaxValue || Value < 0;
                case TypeFlags.Int16:
                    return Value >= short.MaxValue || Value <= short.MinValue;
                case TypeFlags.UInt16:
                case TypeFlags.Char:
                    return Value >= ushort.MaxValue || Value < 0;
                case TypeFlags.Int32:
                    return false;
                case TypeFlags.UInt32:
                    return Value < 0;
                default:
                    return true;
            }
        }
    }

    internal class Int64ConstantEntry : ConstantEntry<long>
    {
        public Int64ConstantEntry(long value, TypeDesc type = null) : base(StackValueKind.Int64, value, type)
        {
        }

        public override StackEntry Duplicate()
        {
            return new Int64ConstantEntry(Value, Type);
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            if (type.TypeKind == LLVMTypeKind.LLVMPointerTypeKind && Value == 0)
            {
                return LLVM.ConstPointerNull(type);
            }
            else if (type.TypeKind == LLVMTypeKind.LLVMPointerTypeKind && Value != 0)
            {
                return LLVM.ConstIntToPtr(LLVM.ConstInt(LLVM.Int64Type(), (ulong)Value, LLVMMisc.False), type);
            }
            else if (type.TypeKind != LLVMTypeKind.LLVMIntegerTypeKind)
            {
                throw new NotImplementedException();
            }
            else
            {
                return LLVM.ConstInt(type, (ulong)Value, LLVMMisc.False);
            }
        }

        public override bool IsCastNecessary(TypeDesc destType)
        {
            switch (destType.UnderlyingType.Category)
            {
                case TypeFlags.SByte:
                    return Value >= sbyte.MaxValue || Value <= sbyte.MinValue;
                case TypeFlags.Byte:
                case TypeFlags.Boolean:
                    return Value >= byte.MaxValue || Value < 0;
                case TypeFlags.Int16:
                    return Value >= short.MaxValue || Value <= short.MinValue;
                case TypeFlags.UInt16:
                case TypeFlags.Char:
                    return Value >= ushort.MaxValue || Value < 0;
                case TypeFlags.Int32:
                    return Value >= int.MaxValue || Value <= int.MinValue;
                case TypeFlags.UInt32:
                    return Value >= uint.MaxValue || Value < 0;
                case TypeFlags.Int64:
                    return false;
                case TypeFlags.UInt64:
                    return Value < 0;
                default:
                    return true;
            }
        }
    }

    internal class FloatConstantEntry : ConstantEntry<double>
    {
        public FloatConstantEntry(double value, TypeDesc type = null) : base(StackValueKind.Float, value, type)
        {
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            return LLVM.ConstReal(type, Value);
        }

        public override StackEntry Duplicate()
        {
            return new FloatConstantEntry(Value, Type);
        }
    }

    /// <summary>
    /// Entry representing some expression
    /// </summary>
    internal class ExpressionEntry : StackEntry
    {
        /// <summary>
        /// String representation of current expression
        /// </summary>
        public string Name { get; set; }
        public LLVMValueRef RawLLVMValue { get; set; }
        /// <summary>
        /// Initializes new instance of ExpressionEntry
        /// </summary>
        /// <param name="kind">Kind of entry</param>
        /// <param name="name">String representation of entry</param>
        /// <param name="type">Type if any of entry</param>
        public ExpressionEntry(StackValueKind kind, string name, LLVMValueRef llvmValue, TypeDesc type = null) : base(kind, type)
        {
            Name = name;
            RawLLVMValue = llvmValue;
        }

        public override StackEntry Duplicate()
        {
            return new ExpressionEntry(Kind, Name, RawLLVMValue, Type);
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            //TODO: deal with sign extension here
            return ILImporter.CastIfNecessary(builder, RawLLVMValue, type);
        }
    }

    internal class LoadExpressionEntry : ExpressionEntry
    {
        /// <summary>
        /// Initializes new instance of ExpressionEntry
        /// </summary>
        /// <param name="kind">Kind of entry</param>
        /// <param name="name">String representation of entry</param>
        /// <param name="type">Type if any of entry</param>
        public LoadExpressionEntry(StackValueKind kind, string name, LLVMValueRef llvmValue, TypeDesc type = null) : base(kind, name, llvmValue, type)
        {
        }

        public override StackEntry Duplicate()
        {
            return new LoadExpressionEntry(Kind, Name, RawLLVMValue, Type);
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            return ILImporter.LoadValue(builder, RawLLVMValue, Type, type, signExtend);
        }
    }

    internal class AddressExpressionEntry : ExpressionEntry
    {
        /// <summary>
        /// Initializes new instance of ExpressionEntry
        /// </summary>
        /// <param name="kind">Kind of entry</param>
        /// <param name="name">String representation of entry</param>
        /// <param name="type">Type if any of entry</param>
        public AddressExpressionEntry(StackValueKind kind, string name, LLVMValueRef llvmValue, TypeDesc type = null) : base(kind, name, llvmValue, type)
        {
        }

        public override StackEntry Duplicate()
        {
            return new LoadExpressionEntry(Kind, Name, RawLLVMValue, Type);
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            return ILImporter.CastIfNecessary(builder, RawLLVMValue, type);
        }
    }

    /// <summary>
    /// Represents the result of a ldftn or ldvirtftn
    /// </summary>
    internal class FunctionPointerEntry : ExpressionEntry
    {
        /// <summary>
        /// True if the function pointer was loaded as a virtual function pointer
        /// </summary>
        public bool IsVirtual { get; }

        public MethodDesc Method { get; }

        public FunctionPointerEntry(string name, MethodDesc method, LLVMValueRef llvmValue, TypeDesc type, bool isVirtual) : base(StackValueKind.NativeInt, name, llvmValue, type)
        {
            Method = method;
            IsVirtual = isVirtual;
        }

        public override StackEntry Duplicate()
        {
            return new FunctionPointerEntry(Name, Method, RawLLVMValue, Type, IsVirtual);
        }
    }

    /// <summary>
    /// Entry representing some token (either of TypeDesc, MethodDesc or FieldDesc) along with its string representation
    /// </summary>
    internal class LdTokenEntry<T> : ExpressionEntry
    {
        public T LdToken { get; }

        public LdTokenEntry(StackValueKind kind, string name, T token, LLVMValueRef llvmValue, TypeDesc type = null) : base(kind, name, llvmValue, type)
        {
            LdToken = token;
        }

        public override StackEntry Duplicate()
        {
            return new LdTokenEntry<T>(Kind, Name, LdToken, RawLLVMValue, Type);
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            if (RawLLVMValue.Pointer == IntPtr.Zero)
                throw new NullReferenceException();

            return ILImporter.CastIfNecessary(builder, RawLLVMValue, type);
        }
    }

    internal class InvalidEntry : StackEntry
    {
        /// <summary>
        /// Entry to use to get an instance of InvalidEntry.
        /// </summary>
        public static InvalidEntry Entry = new InvalidEntry();

        protected InvalidEntry() : base(StackValueKind.Unknown, null)
        {
        }

        public override StackEntry Duplicate()
        {
            return this;
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            throw new InvalidOperationException();
        }
    }

    /// <summary>
    /// Entry representing a writable sharable stack entry that can survive from one basic block to another
    /// </summary>
    internal class SpilledExpressionEntry : ExpressionEntry
    {
        public int LocalIndex;
        private ILImporter _importer;
        public SpilledExpressionEntry(StackValueKind kind, string name, TypeDesc type, int localIndex, ILImporter importer) : base(kind, name, new LLVMValueRef(IntPtr.Zero), type)
        {
            LocalIndex = localIndex;
            _importer = importer;
        }

        protected override LLVMValueRef ValueAsTypeInternal(LLVMTypeRef type, LLVMBuilderRef builder, bool signExtend)
        {
            LLVMTypeRef origLLVMType = ILImporter.GetLLVMTypeForTypeDesc(Type);
            LLVMValueRef value = _importer.LoadTemp(LocalIndex, origLLVMType);

            return ILImporter.CastIfNecessary(builder, value, type);
        }

        public override StackEntry Duplicate()
        {
            return new SpilledExpressionEntry(Kind, Name, Type, LocalIndex, _importer);
        }
    }
}