EmitExpression.cs 139.1 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2

3
using System;
P
Pilchie 已提交
4 5
using System.Collections.Immutable;
using System.Diagnostics;
T
Tomas Matousek 已提交
6
using System.Reflection.Metadata;
P
Pilchie 已提交
7 8 9 10
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;

11
using static System.Linq.ImmutableArrayExtensions;
12
using static Microsoft.CodeAnalysis.CSharp.Binder;
13

P
Pilchie 已提交
14 15
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
16
    internal partial class CodeGenerator
P
Pilchie 已提交
17
    {
18 19 20 21 22
        private int _recursionDepth;

        private class EmitCancelledException : Exception
        { }

23 24 25 26 27 28 29
        private enum UseKind
        {
            Unused,
            UsedAsValue,
            UsedAsAddress
        }

P
Pilchie 已提交
30 31 32 33 34 35 36 37 38 39 40 41
        private void EmitExpression(BoundExpression expression, bool used)
        {
            if (expression == null)
            {
                return;
            }

            var constantValue = expression.ConstantValue;
            if (constantValue != null)
            {
                if (!used)
                {
42
                    // unused constants have no side-effects.
P
Pilchie 已提交
43 44 45 46 47 48 49 50 51 52
                    return;
                }

                if ((object)expression.Type == null || expression.Type.SpecialType != SpecialType.System_Decimal)
                {
                    EmitConstantExpression(expression.Type, constantValue, used, expression.Syntax);
                    return;
                }
            }

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
            _recursionDepth++;

            if (_recursionDepth > 1)
            {
                StackGuard.EnsureSufficientExecutionStack(_recursionDepth);

                EmitExpressionCore(expression, used);
            }
            else
            {
                EmitExpressionCoreWithStackGuard(expression, used);
            }

            _recursionDepth--;
        }

        private void EmitExpressionCoreWithStackGuard(BoundExpression expression, bool used)
        {
            Debug.Assert(_recursionDepth == 1);

            try
            {
                EmitExpressionCore(expression, used);
                Debug.Assert(_recursionDepth == 1);
            }
78
            catch (InsufficientExecutionStackException)
79
            {
C
CyrusNajmabadi 已提交
80
                _diagnostics.Add(ErrorCode.ERR_InsufficientStack,
81 82 83 84 85 86 87
                                 BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(expression));
                throw new EmitCancelledException();
            }
        }

        private void EmitExpressionCore(BoundExpression expression, bool used)
        {
P
Pilchie 已提交
88 89 90
            switch (expression.Kind)
            {
                case BoundKind.AssignmentOperator:
91
                    EmitAssignmentExpression((BoundAssignmentOperator)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
P
Pilchie 已提交
92 93 94
                    break;

                case BoundKind.Call:
95
                    EmitCallExpression((BoundCall)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
P
Pilchie 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109
                    break;

                case BoundKind.ObjectCreationExpression:
                    EmitObjectCreationExpression((BoundObjectCreationExpression)expression, used);
                    break;

                case BoundKind.DelegateCreationExpression:
                    EmitDelegateCreationExpression((BoundDelegateCreationExpression)expression, used);
                    break;

                case BoundKind.ArrayCreation:
                    EmitArrayCreationExpression((BoundArrayCreation)expression, used);
                    break;

110 111
                case BoundKind.ConvertedStackAllocExpression:
                    EmitConvertedStackAllocExpression((BoundConvertedStackAllocExpression)expression, used);
P
Pilchie 已提交
112 113
                    break;

114 115 116 117
                case BoundKind.ReadOnlySpanFromArray:
                    EmitReadOnlySpanFromArrayExpression((BoundReadOnlySpanFromArray)expression, used);
                    break;

P
Pilchie 已提交
118 119 120 121 122 123 124 125 126 127 128 129
                case BoundKind.Conversion:
                    EmitConversionExpression((BoundConversion)expression, used);
                    break;

                case BoundKind.Local:
                    EmitLocalLoad((BoundLocal)expression, used);
                    break;

                case BoundKind.Dup:
                    EmitDupExpression((BoundDup)expression, used);
                    break;

130 131 132 133
                case BoundKind.PassByCopy:
                    EmitExpression(((BoundPassByCopy)expression).Expression, used);
                    break;

P
Pilchie 已提交
134
                case BoundKind.Parameter:
135
                    if (used)  // unused parameter has no side-effects
P
Pilchie 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
                    {
                        EmitParameterLoad((BoundParameter)expression);
                    }
                    break;

                case BoundKind.FieldAccess:
                    EmitFieldLoad((BoundFieldAccess)expression, used);
                    break;

                case BoundKind.ArrayAccess:
                    EmitArrayElementLoad((BoundArrayAccess)expression, used);
                    break;

                case BoundKind.ArrayLength:
                    EmitArrayLength((BoundArrayLength)expression, used);
                    break;

                case BoundKind.ThisReference:
154
                    if (used) // unused this has no side-effects
P
Pilchie 已提交
155 156 157 158 159 160 161 162 163 164
                    {
                        EmitThisReferenceExpression((BoundThisReference)expression);
                    }
                    break;

                case BoundKind.PreviousSubmissionReference:
                    // Script references are lowered to a this reference and a field access.
                    throw ExceptionUtilities.UnexpectedValue(expression.Kind);

                case BoundKind.BaseReference:
165
                    if (used) // unused base has no side-effects
P
Pilchie 已提交
166
                    {
167 168
                        var thisType = _method.ContainingType;
                        _builder.EmitOpCode(ILOpCode.Ldarg_0);
P
Pilchie 已提交
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
                        if (thisType.IsValueType)
                        {
                            EmitLoadIndirect(thisType, expression.Syntax);
                            EmitBox(thisType, expression.Syntax);
                        }
                    }
                    break;

                case BoundKind.Sequence:
                    EmitSequenceExpression((BoundSequence)expression, used);
                    break;

                case BoundKind.SequencePointExpression:
                    EmitSequencePointExpression((BoundSequencePointExpression)expression, used);
                    break;

                case BoundKind.UnaryOperator:
                    EmitUnaryOperatorExpression((BoundUnaryOperator)expression, used);
                    break;

                case BoundKind.BinaryOperator:
                    EmitBinaryOperatorExpression((BoundBinaryOperator)expression, used);
                    break;

                case BoundKind.NullCoalescingOperator:
                    EmitNullCoalescingOperator((BoundNullCoalescingOperator)expression, used);
                    break;

                case BoundKind.IsOperator:
                    EmitIsExpression((BoundIsOperator)expression, used);
                    break;

                case BoundKind.AsOperator:
                    EmitAsExpression((BoundAsOperator)expression, used);
                    break;

205 206
                case BoundKind.DefaultExpression:
                    EmitDefaultExpression((BoundDefaultExpression)expression, used);
P
Pilchie 已提交
207 208 209
                    break;

                case BoundKind.TypeOfOperator:
210
                    if (used) // unused typeof has no side-effects
P
Pilchie 已提交
211 212 213 214 215 216
                    {
                        EmitTypeOfExpression((BoundTypeOfOperator)expression);
                    }
                    break;

                case BoundKind.SizeOfOperator:
217
                    if (used) // unused sizeof has no side-effects
P
Pilchie 已提交
218 219 220 221 222
                    {
                        EmitSizeOfExpression((BoundSizeOfOperator)expression);
                    }
                    break;

223
                case BoundKind.ModuleVersionId:
J
John Hamby 已提交
224 225
                    Debug.Assert(used);
                    EmitModuleVersionIdLoad((BoundModuleVersionId)expression);
226 227
                    break;

J
More.  
John Hamby 已提交
228 229 230 231 232
                case BoundKind.ModuleVersionIdString:
                    Debug.Assert(used);
                    EmitModuleVersionIdStringLoad((BoundModuleVersionIdString)expression);
                    break;

J
John Hamby 已提交
233
                case BoundKind.InstrumentationPayloadRoot:
J
John Hamby 已提交
234
                    Debug.Assert(used);
J
John Hamby 已提交
235
                    EmitInstrumentationPayloadRootLoad((BoundInstrumentationPayloadRoot)expression);
J
John Hamby 已提交
236 237
                    break;

J
John Hamby 已提交
238 239 240
                case BoundKind.MethodDefIndex:
                    Debug.Assert(used);
                    EmitMethodDefIndexExpression((BoundMethodDefIndex)expression);
J
More  
John Hamby 已提交
241 242
                    break;

J
John Hamby 已提交
243
                case BoundKind.MaximumMethodDefIndex:
J
John Hamby 已提交
244
                    Debug.Assert(used);
J
John Hamby 已提交
245
                    EmitMaximumMethodDefIndexExpression((BoundMaximumMethodDefIndex)expression);
J
John Hamby 已提交
246 247
                    break;

248 249 250 251 252
                case BoundKind.SourceDocumentIndex:
                    Debug.Assert(used);
                    EmitSourceDocumentIndex((BoundSourceDocumentIndex)expression);
                    break;

P
Pilchie 已提交
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
                case BoundKind.MethodInfo:
                    if (used)
                    {
                        EmitMethodInfoExpression((BoundMethodInfo)expression);
                    }
                    break;

                case BoundKind.FieldInfo:
                    if (used)
                    {
                        EmitFieldInfoExpression((BoundFieldInfo)expression);
                    }
                    break;

                case BoundKind.ConditionalOperator:
                    EmitConditionalOperator((BoundConditionalOperator)expression, used);
                    break;

                case BoundKind.AddressOfOperator:
                    EmitAddressOfExpression((BoundAddressOfOperator)expression, used);
                    break;

                case BoundKind.PointerIndirectionOperator:
                    EmitPointerIndirectionOperator((BoundPointerIndirectionOperator)expression, used);
                    break;

                case BoundKind.ArgList:
                    EmitArgList(used);
                    break;

                case BoundKind.ArgListOperator:
                    Debug.Assert(used);
                    EmitArgListOperator((BoundArgListOperator)expression);
                    break;

                case BoundKind.RefTypeOperator:
                    EmitRefTypeOperator((BoundRefTypeOperator)expression, used);
                    break;

                case BoundKind.MakeRefOperator:
                    EmitMakeRefOperator((BoundMakeRefOperator)expression, used);
                    break;

                case BoundKind.RefValueOperator:
                    EmitRefValueOperator((BoundRefValueOperator)expression, used);
                    break;

300 301
                case BoundKind.LoweredConditionalAccess:
                    EmitLoweredConditionalAccessExpression((BoundLoweredConditionalAccess)expression, used);
302 303 304 305 306 307
                    break;

                case BoundKind.ConditionalReceiver:
                    EmitConditionalReceiver((BoundConditionalReceiver)expression, used);
                    break;

308 309 310 311
                case BoundKind.ComplexConditionalReceiver:
                    EmitComplexConditionalReceiver((BoundComplexConditionalReceiver)expression, used);
                    break;

312 313 314 315
                case BoundKind.PseudoVariable:
                    EmitPseudoVariableValue((BoundPseudoVariable)expression, used);
                    break;

316 317 318 319
                case BoundKind.ThrowExpression:
                    EmitThrowExpression((BoundThrowExpression)expression, used);
                    break;

P
Pilchie 已提交
320 321 322 323 324 325 326 327 328
                default:
                    // Code gen should not be invoked if there are errors.
                    Debug.Assert(expression.Kind != BoundKind.BadExpression);

                    // node should have been lowered:
                    throw ExceptionUtilities.UnexpectedValue(expression.Kind);
            }
        }

329 330
        private void EmitThrowExpression(BoundThrowExpression node, bool used)
        {
331
            this.EmitThrow(node.Expression);
332 333 334 335 336

            // to satisfy invariants, we push a default value to pretend to adjust the stack height
            EmitDefaultValue(node.Type, used, node.Syntax);
        }

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
        private void EmitComplexConditionalReceiver(BoundComplexConditionalReceiver expression, bool used)
        {
            Debug.Assert(!expression.Type.IsReferenceType);
            Debug.Assert(!expression.Type.IsValueType);

            var receiverType = expression.Type;

            var whenValueTypeLabel = new object();
            var doneLabel = new object();

            EmitInitObj(receiverType, true, expression.Syntax);
            EmitBox(receiverType, expression.Syntax);
            _builder.EmitBranch(ILOpCode.Brtrue, whenValueTypeLabel);

            EmitExpression(expression.ReferenceTypeReceiver, used);
            _builder.EmitBranch(ILOpCode.Br, doneLabel);
            _builder.AdjustStack(-1);

            _builder.MarkLabel(whenValueTypeLabel);
            EmitExpression(expression.ValueTypeReceiver, used);

            _builder.MarkLabel(doneLabel);
        }

361
        private void EmitLoweredConditionalAccessExpression(BoundLoweredConditionalAccess expression, bool used)
362 363 364
        {
            var receiver = expression.Receiver;

365
            var receiverType = receiver.Type;
366
            LocalDefinition receiverTemp = null;
J
Jared Parsons 已提交
367
            Debug.Assert(!receiverType.IsValueType ||
V
VSadov 已提交
368
                (receiverType.IsNullableType() && expression.HasValueMethodOpt != null), "conditional receiver cannot be a struct");
369 370

            var receiverConstant = receiver.ConstantValue;
V
vsadov 已提交
371
            if (receiverConstant?.IsNull == false)
372
            {
V
vsadov 已提交
373
                // const but not null, must be a reference type
374 375
                Debug.Assert(receiverType.IsVerifierReference());
                // receiver is a reference type, so addresskind does not matter, but we do not intend to write.
V
vsadov 已提交
376
                receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
377
                EmitExpression(expression.WhenNotNull, used);
378 379 380 381
                if (receiverTemp != null)
                {
                    FreeTemp(receiverTemp);
                }
382 383 384
                return;
            }

385 386 387
            // labels
            object whenNotNullLabel = new object();
            object doneLabel = new object();
V
VSadov 已提交
388
            LocalDefinition cloneTemp = null;
389

390
            var notConstrained = !receiverType.IsReferenceType && !receiverType.IsValueType;
391

392
            // we need a copy if we deal with nonlocal value (to capture the value)
393
            // or if we have a ref-constrained T (to do box just once) 
394
            // or if we deal with stack local (reads are destructive)
395
            // or if we have default(T) (to do box just once)
396
            var nullCheckOnCopy = LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
397 398
                                   (receiverType.IsReferenceType && receiverType.TypeKind == TypeKind.TypeParameter) ||
                                   (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol));
399

V
VSadov 已提交
400
            // ===== RECEIVER
401 402
            if (nullCheckOnCopy)
            {
403
                if (notConstrained)
404
                {
405 406 407
                    // if T happens to be a value type, it could be a target of mutating calls.
                    receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);

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
                    // unconstrained case needs to handle case where T is actually a struct.
                    // such values are never nulls
                    // we will emit a check for such case, but the check is really a JIT-time 
                    // constant since JIT will know if T is a struct or not.

                    // if ((object)default(T) != null) 
                    // {
                    //     goto whenNotNull
                    // }
                    // else
                    // {
                    //     temp = receiverRef
                    //     receiverRef = ref temp
                    // }
                    EmitDefaultValue(receiverType, true, receiver.Syntax);
                    EmitBox(receiverType, receiver.Syntax);
                    _builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
                    EmitLoadIndirect(receiverType, receiver.Syntax);

                    cloneTemp = AllocateTemp(receiverType, receiver.Syntax);
                    _builder.EmitLocalStore(cloneTemp);
                    _builder.EmitLocalAddress(cloneTemp);
                    _builder.EmitLocalLoad(cloneTemp);
                    EmitBox(receiver.Type, receiver.Syntax);

                    // here we have loaded a ref to a temp and its boxed value { &T, O }
434 435 436
                }
                else
                {
V
vsadov 已提交
437 438
                    // this does not need to be writeable
                    // we may call "HasValue" on this, but it is not mutating 
439
                    var addressKind = AddressKind.ReadOnly;
V
vsadov 已提交
440 441

                    receiverTemp = EmitReceiverRef(receiver, addressKind);
442
                    _builder.EmitOpCode(ILOpCode.Dup);
V
VSadov 已提交
443
                    // here we have loaded two copies of a reference   { O, O }  or  {&nub, &nub}
444 445 446
                }
            }
            else
447
            {
448 449 450 451 452
                // this does not need to be writeable.
                // we may call "HasValue" on this, but it is not mutating
                // besides, since we are not making a copy, the receiver is not a field, 
                // so it cannot be readonly, in verifier sense, anyways.
                receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
V
VSadov 已提交
453 454 455 456 457 458 459 460 461 462 463 464
                // here we have loaded just { O } or  {&nub}
                // we have the most trivial case where we can just reload receiver when needed again
            }

            // ===== CONDITION

            var hasValueOpt = expression.HasValueMethodOpt;
            if (hasValueOpt != null)
            {
                Debug.Assert(receiver.Type.IsNullableType());
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
                EmitSymbolToken(hasValueOpt, expression.Syntax, null);
465 466
            }

467
            _builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
468

V
VSadov 已提交
469 470 471 472 473 474 475 476
            // no longer need the temp if we are not holding a copy
            if (receiverTemp != null && !nullCheckOnCopy)
            {
                FreeTemp(receiverTemp);
                receiverTemp = null;
            }

            // ===== WHEN NULL
477 478
            if (nullCheckOnCopy)
            {
479
                _builder.EmitOpCode(ILOpCode.Pop);
480
            }
481

482 483 484 485 486 487 488 489 490 491
            var whenNull = expression.WhenNullOpt;
            if (whenNull == null)
            {
                EmitDefaultValue(expression.Type, used, expression.Syntax);
            }
            else
            {
                EmitExpression(whenNull, used);
            }

492
            _builder.EmitBranch(ILOpCode.Br, doneLabel);
493

V
VSadov 已提交
494 495

            // ===== WHEN NOT NULL 
496
            if (nullCheckOnCopy)
497
            {
498 499 500
                // notNull branch pops copy of receiver off the stack when nullCheckOnCopy
                // however on the isNull branch we still have the stack as it was and need 
                // to adjust stack depth correspondingly.
501
                _builder.AdjustStack(+1);
502
            }
503 504 505 506 507 508

            if (used)
            {
                // notNull branch pushes default on the stack when used
                // however on the isNull branch we still have the stack as it was and need 
                // to adjust stack depth correspondingly.
509
                _builder.AdjustStack(-1);
510 511
            }

512
            _builder.MarkLabel(whenNotNullLabel);
513 514 515

            if (!nullCheckOnCopy)
            {
V
VSadov 已提交
516
                Debug.Assert(receiverTemp == null);
C
Charles Stoner 已提交
517
                // receiver may be used as target of a struct call (if T happens to be a struct)
518
                receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
V
VSadov 已提交
519
                Debug.Assert(receiverTemp == null || receiver.IsDefaultValue());
520 521
            }

522
            EmitExpression(expression.WhenNotNull, used);
V
VSadov 已提交
523 524

            // ===== DONE
525
            _builder.MarkLabel(doneLabel);
526

V
VSadov 已提交
527
            if (cloneTemp != null)
528
            {
V
VSadov 已提交
529
                FreeTemp(cloneTemp);
530
            }
531 532 533 534 535

            if (receiverTemp != null)
            {
                FreeTemp(receiverTemp);
            }
536 537 538 539
        }

        private void EmitConditionalReceiver(BoundConditionalReceiver expression, bool used)
        {
540 541 542 543 544 545 546
            Debug.Assert(!expression.Type.IsValueType);

            if (!expression.Type.IsReferenceType)
            {
                EmitLoadIndirect(expression.Type, expression.Syntax);
            }

547 548 549
            EmitPopIfUnused(used);
        }

P
Pilchie 已提交
550 551 552 553 554 555 556 557 558 559 560 561
        private void EmitRefValueOperator(BoundRefValueOperator expression, bool used)
        {
            EmitRefValueAddress(expression);
            EmitLoadIndirect(expression.Type, expression.Syntax);
            EmitPopIfUnused(used);
        }

        private void EmitMakeRefOperator(BoundMakeRefOperator expression, bool used)
        {
            // push address of variable
            // mkrefany [Type] -- takes address off stack, puts TypedReference on stack

562 563 564
            var temp = EmitAddress(expression.Operand, AddressKind.Writeable);
            Debug.Assert(temp == null, "makeref should not create temps");

565
            _builder.EmitOpCode(ILOpCode.Mkrefany);
P
Pilchie 已提交
566 567 568 569 570 571 572 573 574 575 576
            EmitSymbolToken(expression.Operand.Type, expression.Operand.Syntax);
            EmitPopIfUnused(used);
        }

        private void EmitRefTypeOperator(BoundRefTypeOperator expression, bool used)
        {
            // push TypedReference
            // refanytype -- takes TypedReference off stack, puts token on stack
            // call GetTypeFromHandle -- takes token off stack, puts Type on stack

            EmitExpression(expression.Operand, true);
577 578
            _builder.EmitOpCode(ILOpCode.Refanytype);
            _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
P
Pilchie 已提交
579 580 581 582 583 584 585 586
            var getTypeMethod = expression.GetTypeFromHandle;
            Debug.Assert((object)getTypeMethod != null);
            EmitSymbolToken(getTypeMethod, expression.Syntax, null);
            EmitPopIfUnused(used);
        }

        private void EmitArgList(bool used)
        {
587
            _builder.EmitOpCode(ILOpCode.Arglist);
P
Pilchie 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
            EmitPopIfUnused(used);
        }

        private void EmitArgListOperator(BoundArgListOperator expression)
        {
            for (int i = 0; i < expression.Arguments.Length; i++)
            {
                BoundExpression argument = expression.Arguments[i];
                RefKind refKind = expression.ArgumentRefKindsOpt.IsDefaultOrEmpty ? RefKind.None : expression.ArgumentRefKindsOpt[i];
                EmitArgument(argument, refKind);
            }
        }

        private void EmitArgument(BoundExpression argument, RefKind refKind)
        {
603
            switch (refKind)
P
Pilchie 已提交
604
            {
V
vsadov 已提交
605 606 607
                case RefKind.None:
                    EmitExpression(argument, true);
                    break;
608

609
                case RefKind.In:
V
vsadov 已提交
610
                    var temp = EmitAddress(argument, AddressKind.ReadOnly);
V
vsadov 已提交
611
                    AddExpressionTemp(temp);
V
vsadov 已提交
612 613 614
                    break;

                default:
615 616
                    // NOTE: passing "ReadOnlyStrict" here. 
                    //       we should not get an address of a copy if at all possible
D
dotnet-bot 已提交
617
                    var unexpectedTemp = EmitAddress(argument, refKind == RefKindExtensions.StrictIn ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
V
vsadov 已提交
618 619 620 621 622 623 624
                    if (unexpectedTemp != null)
                    {
                        // interestingly enough "ref dynamic" sometimes is passed via a clone
                        Debug.Assert(argument.Type.IsDynamic(), "passing args byref should not clone them into temps");
                        AddExpressionTemp(unexpectedTemp);
                    }

V
vsadov 已提交
625
                    break;
P
Pilchie 已提交
626 627 628 629 630
            }
        }

        private void EmitAddressOfExpression(BoundAddressOfOperator expression, bool used)
        {
631 632 633
            // NOTE: passing "ReadOnlyStrict" here. 
            //       we should not get an address of a copy if at all possible
            var temp = EmitAddress(expression.Operand, AddressKind.ReadOnlyStrict);
P
Pilchie 已提交
634
            Debug.Assert(temp == null, "If the operand is addressable, then a temp shouldn't be required.");
635

636
            if (used && !expression.IsManaged)
P
Pilchie 已提交
637 638 639 640 641 642 643
            {
                // When computing an address to be used to initialize a fixed-statement variable, we have to be careful
                // not to convert the managed reference to an unmanaged pointer before storing it.  Otherwise the GC might
                // come along and move memory around, invalidating the pointer before it is pinned by being stored in
                // the fixed variable.  But elsewhere in the code we do use a conv.u instruction to convert the managed
                // reference to the underlying type for unmanaged pointers, which is the type "unsigned int" (see CLI
                // standard, Partition I section 12.1.1.1).
644
                _builder.EmitOpCode(ILOpCode.Conv_u);
P
Pilchie 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
            }

            EmitPopIfUnused(used);
        }

        private void EmitPointerIndirectionOperator(BoundPointerIndirectionOperator expression, bool used)
        {
            EmitExpression(expression.Operand, used: true);
            EmitLoadIndirect(expression.Type, expression.Syntax);
            EmitPopIfUnused(used);
        }

        private void EmitDupExpression(BoundDup expression, bool used)
        {
            if (expression.RefKind == RefKind.None)
            {
                // unused dup is noop
                if (used)
                {
664
                    _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
665 666 667 668
                }
            }
            else
            {
669
                _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
670 671 672 673 674 675 676 677 678

                // must read in case if it is a null ref
                EmitLoadIndirect(expression.Type, expression.Syntax);
                EmitPopIfUnused(used);
            }
        }

        private void EmitDelegateCreationExpression(BoundDelegateCreationExpression expression, bool used)
        {
679 680
            var mg = expression.Argument as BoundMethodGroup;
            var receiver = mg != null ? mg.ReceiverOpt : expression.Argument;
681
            var meth = expression.MethodOpt ?? receiver.Type.DelegateInvokeMethod();
P
Pilchie 已提交
682 683 684 685 686 687 688 689 690
            Debug.Assert((object)meth != null);
            EmitDelegateCreation(expression, receiver, expression.IsExtensionMethod, meth, expression.Type, used);
        }

        private void EmitThisReferenceExpression(BoundThisReference thisRef)
        {
            var thisType = thisRef.Type;
            Debug.Assert(thisType.TypeKind != TypeKind.TypeParameter);

691
            _builder.EmitOpCode(ILOpCode.Ldarg_0);
P
Pilchie 已提交
692 693 694 695 696 697
            if (thisType.IsValueType)
            {
                EmitLoadIndirect(thisType, thisRef.Syntax);
            }
        }

698 699
        private void EmitPseudoVariableValue(BoundPseudoVariable expression, bool used)
        {
700
            EmitExpression(expression.EmitExpressions.GetValue(expression, _diagnostics), used);
701 702
        }

P
Pilchie 已提交
703
        private void EmitSequencePointExpression(BoundSequencePointExpression node, bool used)
704 705 706 707 708 709 710 711 712
        {
            EmitSequencePoint(node);

            // used is true to ensure that something is emitted
            EmitExpression(node.Expression, used: true);
            EmitPopIfUnused(used);
        }

        private void EmitSequencePoint(BoundSequencePointExpression node)
P
Pilchie 已提交
713 714
        {
            var syntax = node.Syntax;
715
            if (_emitPdbSequencePoints)
P
Pilchie 已提交
716 717 718 719 720 721 722
            {
                if (syntax == null)
                {
                    EmitHiddenSequencePoint();
                }
                else
                {
723
                    EmitSequencePoint(syntax);
P
Pilchie 已提交
724 725 726 727 728 729
                }
            }
        }

        private void EmitSequenceExpression(BoundSequence sequence, bool used)
        {
730
            DefineLocals(sequence);
P
Pilchie 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743 744
            EmitSideEffects(sequence);

            // CONSIDER:    LocalRewriter.RewriteNestedObjectOrCollectionInitializerExpression may create a bound sequence with an unused BoundTypeExpression as the value,
            // CONSIDER:    which must be ignored by codegen. See comments in RewriteNestedObjectOrCollectionInitializerExpression for details and an example.
            // CONSIDER:    We may want to instead consider making the Value field of BoundSequence node optional to allow a sequence with
            // CONSIDER:    only side effects and no value. Note that VB's BoundSequence node has an optional value field.
            // CONSIDER:    This will allow us to remove the below check before emitting the value.

            Debug.Assert(sequence.Value.Kind != BoundKind.TypeExpression || !used);
            if (sequence.Value.Kind != BoundKind.TypeExpression)
            {
                EmitExpression(sequence.Value, used);
            }

745
            // sequence is used as a value, can release all locals
746
            FreeLocals(sequence);
747 748 749 750 751
        }

        private void DefineLocals(BoundSequence sequence)
        {
            if (sequence.Locals.IsEmpty)
P
Pilchie 已提交
752
            {
753 754
                return;
            }
P
Pilchie 已提交
755

756
            _builder.OpenLocalScope();
757 758 759 760 761 762 763

            foreach (var local in sequence.Locals)
            {
                DefineLocal(local, sequence.Syntax);
            }
        }

764
        private void FreeLocals(BoundSequence sequence)
765 766 767 768 769 770
        {
            if (sequence.Locals.IsEmpty)
            {
                return;
            }

771
            _builder.CloseLocalScope();
772 773 774

            foreach (var local in sequence.Locals)
            {
775 776 777 778 779
                FreeLocal(local);
            }
        }

        /// <summary>
C
Charles Stoner 已提交
780
        /// Defines sequence locals and record them so that they could be retained for the duration of the encompassing expression
V
vsadov 已提交
781
        /// Use this when taking a reference of the sequence, which can indirectly refer to any of its locals.
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
        /// </summary>
        private void DefineAndRecordLocals(BoundSequence sequence)
        {
            if (sequence.Locals.IsEmpty)
            {
                return;
            }

            _builder.OpenLocalScope();

            foreach (var local in sequence.Locals)
            {
                var seqLocal = DefineLocal(local, sequence.Syntax);
                AddExpressionTemp(seqLocal);
            }
        }

        /// <summary>
        /// Closes the visibility/debug scopes for the sequence locals, but keep the local slots from reuse
C
Charles Stoner 已提交
801
        /// for the duration of the encompassing expression.
802 803 804 805 806 807 808
        /// Use this paired with DefineAndRecordLocals when taking a reference of the sequence, which can indirectly refer to any of its locals.
        /// </summary>
        private void CloseScopeAndKeepLocals(BoundSequence sequence)
        {
            if (sequence.Locals.IsEmpty)
            {
                return;
P
Pilchie 已提交
809
            }
810 811

            _builder.CloseLocalScope();
P
Pilchie 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825
        }

        private void EmitSideEffects(BoundSequence sequence)
        {
            var sideEffects = sequence.SideEffects;
            if (!sideEffects.IsDefaultOrEmpty)
            {
                foreach (var se in sideEffects)
                {
                    EmitExpression(se, false);
                }
            }
        }

826
        private void EmitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt)
P
Pilchie 已提交
827 828 829
        {
            // We might have an extra argument for the __arglist() of a varargs method.
            Debug.Assert(arguments.Length == parameters.Length || arguments.Length == parameters.Length + 1, "argument count must match parameter count");
830 831 832
            Debug.Assert(parameters.All(p => p.RefKind == RefKind.None) || !argRefKindsOpt.IsDefault, "there are nontrivial parameters, so we must have argRefKinds");
            Debug.Assert(argRefKindsOpt.IsDefault || argRefKindsOpt.Length == arguments.Length, "if we have argRefKinds, we should have one for each argument");

P
Pilchie 已提交
833 834
            for (int i = 0; i < arguments.Length; i++)
            {
V
vsadov 已提交
835 836 837 838
                RefKind argRefKind = GetArgumentRefKind(arguments, parameters, argRefKindsOpt, i);
                EmitArgument(arguments[i], argRefKind);
            }
        }
839

V
vsadov 已提交
840 841
        /// <summary>
        /// Computes the desired refkind of the argument.
V
vsadov 已提交
842
        /// Considers all the cases - where ref kinds are explicit, omitted, vararg cases.
V
vsadov 已提交
843 844 845 846 847 848 849
        /// </summary>
        internal static RefKind GetArgumentRefKind(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt, int i)
        {
            RefKind argRefKind;
            if (i < parameters.Length)
            {
                if (!argRefKindsOpt.IsDefault && i < argRefKindsOpt.Length)
850
                {
V
vsadov 已提交
851 852
                    // if we have an explicit refKind for the given argument, use that
                    argRefKind = argRefKindsOpt[i];
853

V
vsadov 已提交
854 855 856
                    Debug.Assert(argRefKind == parameters[i].RefKind ||
                            argRefKind == RefKindExtensions.StrictIn && parameters[i].RefKind == RefKind.In,
                            "in Emit the argument RefKind must be compatible with the corresponding parameter");
857 858 859
                }
                else
                {
V
vsadov 已提交
860 861
                    // otherwise fallback to the refKind of the parameter
                    argRefKind = parameters[i].RefKind;
862
                }
P
Pilchie 已提交
863
            }
V
vsadov 已提交
864 865 866 867 868 869 870 871
            else
            {
                // vararg case
                Debug.Assert(arguments[i].Kind == BoundKind.ArgListOperator);
                argRefKind = RefKind.None;
            }

            return argRefKind;
P
Pilchie 已提交
872 873 874 875 876 877 878
        }

        private void EmitArrayElementLoad(BoundArrayAccess arrayAccess, bool used)
        {
            EmitExpression(arrayAccess.Expression, used: true);
            EmitArrayIndices(arrayAccess.Indices);

879
            if (((ArrayTypeSymbol)arrayAccess.Expression.Type).IsSZArray)
P
Pilchie 已提交
880 881 882 883 884 885 886 887 888 889 890
            {
                var elementType = arrayAccess.Type;
                if (elementType.IsEnumType())
                {
                    //underlying primitives do not need type tokens.
                    elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
                }

                switch (elementType.PrimitiveTypeCode)
                {
                    case Microsoft.Cci.PrimitiveTypeCode.Int8:
891
                        _builder.EmitOpCode(ILOpCode.Ldelem_i1);
P
Pilchie 已提交
892 893
                        break;

894
                    case Microsoft.Cci.PrimitiveTypeCode.Boolean:
P
Pilchie 已提交
895
                    case Microsoft.Cci.PrimitiveTypeCode.UInt8:
896
                        _builder.EmitOpCode(ILOpCode.Ldelem_u1);
P
Pilchie 已提交
897 898 899
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Int16:
900
                        _builder.EmitOpCode(ILOpCode.Ldelem_i2);
P
Pilchie 已提交
901 902 903 904
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Char:
                    case Microsoft.Cci.PrimitiveTypeCode.UInt16:
905
                        _builder.EmitOpCode(ILOpCode.Ldelem_u2);
P
Pilchie 已提交
906 907 908
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Int32:
909
                        _builder.EmitOpCode(ILOpCode.Ldelem_i4);
P
Pilchie 已提交
910 911 912
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.UInt32:
913
                        _builder.EmitOpCode(ILOpCode.Ldelem_u4);
P
Pilchie 已提交
914 915 916 917
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Int64:
                    case Microsoft.Cci.PrimitiveTypeCode.UInt64:
918
                        _builder.EmitOpCode(ILOpCode.Ldelem_i8);
P
Pilchie 已提交
919 920 921 922 923
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                    case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                    case Microsoft.Cci.PrimitiveTypeCode.Pointer:
924
                        _builder.EmitOpCode(ILOpCode.Ldelem_i);
P
Pilchie 已提交
925 926 927
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Float32:
928
                        _builder.EmitOpCode(ILOpCode.Ldelem_r4);
P
Pilchie 已提交
929 930 931
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Float64:
932
                        _builder.EmitOpCode(ILOpCode.Ldelem_r8);
P
Pilchie 已提交
933 934 935 936 937
                        break;

                    default:
                        if (elementType.IsVerifierReference())
                        {
938
                            _builder.EmitOpCode(ILOpCode.Ldelem_ref);
P
Pilchie 已提交
939 940 941 942 943
                        }
                        else
                        {
                            if (used)
                            {
944
                                _builder.EmitOpCode(ILOpCode.Ldelem);
P
Pilchie 已提交
945 946 947 948
                            }
                            else
                            {
                                // no need to read whole element of nontrivial type/size here
949
                                // just take a reference to an element for array access side-effects 
P
Pilchie 已提交
950 951
                                if (elementType.TypeKind == TypeKind.TypeParameter)
                                {
952
                                    _builder.EmitOpCode(ILOpCode.Readonly);
P
Pilchie 已提交
953 954
                                }

955
                                _builder.EmitOpCode(ILOpCode.Ldelema);
P
Pilchie 已提交
956 957 958 959 960 961 962 963 964
                            }

                            EmitSymbolToken(elementType, arrayAccess.Syntax);
                        }
                        break;
                }
            }
            else
            {
965
                _builder.EmitArrayElementLoad(Emit.PEModuleBuilder.Translate((ArrayTypeSymbol)arrayAccess.Expression.Type), arrayAccess.Expression.Syntax, _diagnostics);
P
Pilchie 已提交
966 967 968 969 970 971 972 973 974
            }

            EmitPopIfUnused(used);
        }

        private void EmitFieldLoad(BoundFieldAccess fieldAccess, bool used)
        {
            var field = fieldAccess.FieldSymbol;

975
            if (!used)
P
Pilchie 已提交
976
            {
977
                // fetching unused captured frame is a no-op (like reading "this")
V
VSadov 已提交
978
                if (field.IsCapturedFrame)
979 980 981 982
                {
                    return;
                }

V
VSadov 已提交
983 984
                // Accessing a volatile field is sideeffecting because it establishes an acquire fence.
                // Otherwise, accessing an unused instance field on a struct is a noop. Just emit an unused receiver.
985 986 987 988 989
                if (!field.IsVolatile && !field.IsStatic && fieldAccess.ReceiverOpt.Type.IsVerifierValue())
                {
                    EmitExpression(fieldAccess.ReceiverOpt, used: false);
                    return;
                }
P
Pilchie 已提交
990 991 992 993 994
            }

            Debug.Assert(!field.IsConst || field.ContainingType.SpecialType == SpecialType.System_Decimal,
                "rewriter should lower constant fields into constant expressions");

C
Charles Stoner 已提交
995
            // static field access is sideeffecting since it guarantees that ..ctor has run.
V
VSadov 已提交
996
            // we emit static accesses even if unused.
P
Pilchie 已提交
997 998 999 1000
            if (field.IsStatic)
            {
                if (field.IsVolatile)
                {
1001
                    _builder.EmitOpCode(ILOpCode.Volatile);
P
Pilchie 已提交
1002
                }
1003
                _builder.EmitOpCode(ILOpCode.Ldsfld);
P
Pilchie 已提交
1004 1005 1006 1007 1008
                EmitSymbolToken(field, fieldAccess.Syntax);
            }
            else
            {
                var receiver = fieldAccess.ReceiverOpt;
1009
                TypeSymbol fieldType = field.Type;
P
Pilchie 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
                if (fieldType.IsValueType && (object)fieldType == (object)receiver.Type)
                {
                    //Handle emitting a field of a self-containing struct (only possible in mscorlib)
                    //since "val.field" is the same as val, we only need to emit val.
                    EmitExpression(receiver, used);
                }
                else
                {
                    var temp = EmitFieldLoadReceiver(receiver);
                    if (temp != null)
                    {
1021
                        Debug.Assert(FieldLoadMustUseRef(receiver), "only clr-ambiguous structs use temps here");
P
Pilchie 已提交
1022 1023 1024 1025 1026
                        FreeTemp(temp);
                    }

                    if (field.IsVolatile)
                    {
1027
                        _builder.EmitOpCode(ILOpCode.Volatile);
P
Pilchie 已提交
1028 1029
                    }

1030
                    _builder.EmitOpCode(ILOpCode.Ldfld);
P
Pilchie 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
                    EmitSymbolToken(field, fieldAccess.Syntax);
                }
            }
            EmitPopIfUnused(used);
        }

        private LocalDefinition EmitFieldLoadReceiver(BoundExpression receiver)
        {
            // ldfld can work with structs directly or with their addresses
            // accessing via address is typically same or cheaper, but not for homeless values, obviously
            // there are also cases where we must emit receiver as a reference
            if (FieldLoadMustUseRef(receiver) || FieldLoadPrefersRef(receiver))
            {
V
vsadov 已提交
1044
                return EmitFieldLoadReceiverAddress(receiver) ? null : EmitReceiverRef(receiver, AddressKind.ReadOnly);
P
Pilchie 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
            }

            EmitExpression(receiver, true);
            return null;
        }

        // In special case of loading the sequence of field accesses we can perform all the 
        // necessary field loads using the following IL: 
        //
        //      <expr>.a.b...y.z
        //          |
        //          V
        //      Unbox -or- Load.Ref (<expr>)
        //      Ldflda a
        //      Ldflda b
        //      ...
        //      Ldflda y
        //      Ldfld z
        //
        // Returns 'true' if the receiver was actually emitted this way
        private bool EmitFieldLoadReceiverAddress(BoundExpression receiver)
        {
1067
            if (receiver == null || !receiver.Type.IsValueType)
P
Pilchie 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076
            {
                return false;
            }
            else if (receiver.Kind == BoundKind.Conversion)
            {
                var conversion = (BoundConversion)receiver;
                if (conversion.ConversionKind == ConversionKind.Unboxing)
                {
                    EmitExpression(conversion.Operand, true);
1077
                    _builder.EmitOpCode(ILOpCode.Unbox);
P
Pilchie 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
                    EmitSymbolToken(receiver.Type, receiver.Syntax);
                    return true;
                }
            }
            else if (receiver.Kind == BoundKind.FieldAccess)
            {
                var fieldAccess = (BoundFieldAccess)receiver;
                var field = fieldAccess.FieldSymbol;

                if (!field.IsStatic && EmitFieldLoadReceiverAddress(fieldAccess.ReceiverOpt))
                {
B
bkoelman 已提交
1089
                    Debug.Assert(!field.IsVolatile, "volatile valuetype fields are unexpected");
P
Pilchie 已提交
1090

1091
                    _builder.EmitOpCode(ILOpCode.Ldflda);
P
Pilchie 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
                    EmitSymbolToken(field, fieldAccess.Syntax);
                    return true;
                }
            }

            return false;
        }

        // ldfld can work with structs directly or with their addresses
        // In some cases it results in same native code emitted, but in some cases JIT pushes values for real
        // resulting in much worse code (on x64 in particular).
        // So, we will always prefer references here except when receiver is a struct non-ref local or parameter. 
        private bool FieldLoadPrefersRef(BoundExpression receiver)
        {
            // only fields of structs can be accessed via value
            if (!receiver.Type.IsVerifierValue())
            {
                return true;
            }

            // can unbox directly into a ref.
            if (receiver.Kind == BoundKind.Conversion && ((BoundConversion)receiver).ConversionKind == ConversionKind.Unboxing)
            {
                return true;
            }

            // can we take address at all?
1119
            if (!HasHome(receiver, AddressKind.ReadOnly))
P
Pilchie 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
            {
                return false;
            }

            switch (receiver.Kind)
            {
                case BoundKind.Parameter:
                    // prefer ldarg over ldarga
                    return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;

                case BoundKind.Local:
                    // prefer ldloc over ldloca
                    return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;

                case BoundKind.Sequence:
                    return FieldLoadPrefersRef(((BoundSequence)receiver).Value);

                case BoundKind.FieldAccess:
                    var fieldAccess = (BoundFieldAccess)receiver;
                    if (fieldAccess.FieldSymbol.IsStatic)
                    {
                        return true;
                    }

1144
                    if (DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
P
Pilchie 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
                    {
                        return false;
                    }

                    return FieldLoadPrefersRef(fieldAccess.ReceiverOpt);
            }

            return true;
        }

        internal static bool FieldLoadMustUseRef(BoundExpression expr)
        {
            var type = expr.Type;

            // type parameter values must be boxed to get access to fields
            if (type.IsTypeParameter())
            {
                return true;
            }

            // From   Dev12/symbol.cpp
            //  
            //  // Used by ILGEN to determine if the type of this AggregateSymbol is one that the CLR
            //  // will consider ambiguous to an unmanaged pointer when it is on the stack (see VSW #396011)
            //  bool AggregateSymbol::IsCLRAmbigStruct()
            //      . . .
            switch (type.SpecialType)
            {
                // case PT_BYTE:
                case SpecialType.System_Byte:
                // case PT_SHORT:
                case SpecialType.System_Int16:
                // case PT_INT:
                case SpecialType.System_Int32:
                // case PT_LONG:
                case SpecialType.System_Int64:
                // case PT_CHAR:
                case SpecialType.System_Char:
                // case PT_BOOL:
                case SpecialType.System_Boolean:
                // case PT_SBYTE:
                case SpecialType.System_SByte:
                // case PT_USHORT:
                case SpecialType.System_UInt16:
                // case PT_UINT:
                case SpecialType.System_UInt32:
                // case PT_ULONG:
                case SpecialType.System_UInt64:
                // case PT_INTPTR:
                case SpecialType.System_IntPtr:
                // case PT_UINTPTR:
                case SpecialType.System_UIntPtr:
                // case PT_FLOAT:
                case SpecialType.System_Single:
                // case PT_DOUBLE:
                case SpecialType.System_Double:
                // case PT_TYPEHANDLE:
                case SpecialType.System_RuntimeTypeHandle:
                // case PT_FIELDHANDLE:
                case SpecialType.System_RuntimeFieldHandle:
                // case PT_METHODHANDLE:
                case SpecialType.System_RuntimeMethodHandle:
                //case PT_ARGUMENTHANDLE:
                case SpecialType.System_RuntimeArgumentHandle:
                    return true;
            }

            // this is for value__
            // I do not know how to hit this, since value__ is not bindable in C#, but Dev12 has code to handle this
            return type.IsEnumType();
        }


        private static int ParameterSlot(BoundParameter parameter)
        {
            var sym = parameter.ParameterSymbol;
            int slot = sym.Ordinal;
            if (!sym.ContainingSymbol.IsStatic)
            {
                slot++;  // skip "this"
            }
            return slot;
        }

        private void EmitLocalLoad(BoundLocal local, bool used)
        {
            if (IsStackLocal(local.LocalSymbol))
            {
                // local must be already on the stack
                EmitPopIfUnused(used);
            }
            else
            {
                if (used)
                {
                    LocalDefinition definition = GetLocal(local);
1241
                    _builder.EmitLocalLoad(definition);
P
Pilchie 已提交
1242 1243 1244
                }
                else
                {
1245
                    // do nothing. Unused local load has no side-effects.
P
Pilchie 已提交
1246 1247 1248 1249 1250 1251
                    return;
                }
            }

            if (used && local.LocalSymbol.RefKind != RefKind.None)
            {
1252
                EmitLoadIndirect(local.LocalSymbol.Type, local.Syntax);
P
Pilchie 已提交
1253 1254 1255 1256 1257 1258
            }
        }

        private void EmitParameterLoad(BoundParameter parameter)
        {
            int slot = ParameterSlot(parameter);
1259
            _builder.EmitLoadArgumentOpcode(slot);
P
Pilchie 已提交
1260 1261 1262

            if (parameter.ParameterSymbol.RefKind != RefKind.None)
            {
1263
                var parameterType = parameter.ParameterSymbol.Type;
P
Pilchie 已提交
1264 1265 1266 1267
                EmitLoadIndirect(parameterType, parameter.Syntax);
            }
        }

1268
        private void EmitLoadIndirect(TypeSymbol type, SyntaxNode syntaxNode)
P
Pilchie 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
        {
            if (type.IsEnumType())
            {
                //underlying primitives do not need type tokens.
                type = ((NamedTypeSymbol)type).EnumUnderlyingType;
            }

            switch (type.PrimitiveTypeCode)
            {
                case Microsoft.Cci.PrimitiveTypeCode.Int8:
1279
                    _builder.EmitOpCode(ILOpCode.Ldind_i1);
P
Pilchie 已提交
1280 1281
                    break;

1282
                case Microsoft.Cci.PrimitiveTypeCode.Boolean:
P
Pilchie 已提交
1283
                case Microsoft.Cci.PrimitiveTypeCode.UInt8:
1284
                    _builder.EmitOpCode(ILOpCode.Ldind_u1);
P
Pilchie 已提交
1285 1286 1287
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int16:
1288
                    _builder.EmitOpCode(ILOpCode.Ldind_i2);
P
Pilchie 已提交
1289 1290 1291 1292
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Char:
                case Microsoft.Cci.PrimitiveTypeCode.UInt16:
1293
                    _builder.EmitOpCode(ILOpCode.Ldind_u2);
P
Pilchie 已提交
1294 1295 1296
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int32:
1297
                    _builder.EmitOpCode(ILOpCode.Ldind_i4);
P
Pilchie 已提交
1298 1299 1300
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.UInt32:
1301
                    _builder.EmitOpCode(ILOpCode.Ldind_u4);
P
Pilchie 已提交
1302 1303 1304 1305
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int64:
                case Microsoft.Cci.PrimitiveTypeCode.UInt64:
1306
                    _builder.EmitOpCode(ILOpCode.Ldind_i8);
P
Pilchie 已提交
1307 1308 1309 1310 1311
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.Pointer:
1312
                    _builder.EmitOpCode(ILOpCode.Ldind_i);
P
Pilchie 已提交
1313 1314 1315
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float32:
1316
                    _builder.EmitOpCode(ILOpCode.Ldind_r4);
P
Pilchie 已提交
1317 1318 1319
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float64:
1320
                    _builder.EmitOpCode(ILOpCode.Ldind_r8);
P
Pilchie 已提交
1321 1322 1323 1324 1325
                    break;

                default:
                    if (type.IsVerifierReference())
                    {
1326
                        _builder.EmitOpCode(ILOpCode.Ldind_ref);
P
Pilchie 已提交
1327 1328 1329
                    }
                    else
                    {
1330
                        _builder.EmitOpCode(ILOpCode.Ldobj);
P
Pilchie 已提交
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
                        EmitSymbolToken(type, syntaxNode);
                    }
                    break;
            }
        }

        /// <summary>
        /// Used to decide if we need to emit call or callvirt.
        /// It basically checks if the receiver expression cannot be null, but it is not 100% precise. 
        /// There are cases where it really can be null, but we do not care.
        /// </summary>
        private bool CanUseCallOnRefTypeReceiver(BoundExpression receiver)
        {
            // It seems none of the ways that could produce a receiver typed as a type param 
1345
            // can guarantee that it is not null.
P
Pilchie 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
            if (receiver.Type.IsTypeParameter())
            {
                return false;
            }

            Debug.Assert(receiver.Type.IsVerifierReference(), "this is not a reference");
            Debug.Assert(receiver.Kind != BoundKind.BaseReference, "base should always use call");

            var constVal = receiver.ConstantValue;
            if (constVal != null)
            {
                // only when this is a constant Null, we need a callvirt
                return !constVal.IsNull;
            }

            switch (receiver.Kind)
            {
                case BoundKind.ArrayCreation:
                    return true;

                case BoundKind.ObjectCreationExpression:
V
VSadov 已提交
1367 1368
                    // NOTE: there are cases involving ProxyAttribute
                    // where newobj may produce null
P
Pilchie 已提交
1369 1370 1371 1372 1373 1374 1375 1376
                    return true;

                case BoundKind.Conversion:
                    var conversion = (BoundConversion)receiver;

                    switch (conversion.ConversionKind)
                    {
                        case ConversionKind.Boxing:
V
VSadov 已提交
1377 1378
                            // NOTE: boxing can produce null for Nullable, but any call through that
                            // will result in null reference exceptions anyways.
P
Pilchie 已提交
1379 1380 1381 1382
                            return true;

                        case ConversionKind.MethodGroup:
                        case ConversionKind.AnonymousFunction:
1383
                            return true;
P
Pilchie 已提交
1384 1385 1386 1387 1388 1389 1390 1391

                        case ConversionKind.ExplicitReference:
                        case ConversionKind.ImplicitReference:
                            return CanUseCallOnRefTypeReceiver(conversion.Operand);
                    }
                    break;

                case BoundKind.ThisReference:
V
VSadov 已提交
1392 1393 1394 1395
                    // NOTE: these actually can be null if called from a different language
                    // however, we assume it is responsibility of the caller to nullcheck "this"
                    // if we already have access to "this", we must be in a member and should 
                    // not redo the check
P
Pilchie 已提交
1396 1397
                    return true;

1398 1399 1400 1401 1402 1403 1404 1405
                case BoundKind.FieldAccess:
                    // same reason as for "ThisReference"
                    return ((BoundFieldAccess)receiver).FieldSymbol.IsCapturedFrame;

                case BoundKind.Local:
                    // same reason as for "ThisReference"
                    return ((BoundLocal)receiver).LocalSymbol.SynthesizedKind == SynthesizedLocalKind.FrameCache;

P
Pilchie 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
                case BoundKind.DelegateCreationExpression:
                    return true;

                case BoundKind.Sequence:
                    var seqValue = ((BoundSequence)(receiver)).Value;
                    return CanUseCallOnRefTypeReceiver(seqValue);

                case BoundKind.AssignmentOperator:
                    var rhs = ((BoundAssignmentOperator)receiver).Right;
                    return CanUseCallOnRefTypeReceiver(rhs);

                case BoundKind.TypeOfOperator:
                    return true;

1420 1421 1422
                case BoundKind.ConditionalReceiver:
                    return true;

P
Pilchie 已提交
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
                    //TODO: there could be more cases where we can be sure that receiver is not a null.
            }

            return false;
        }

        /// <summary>
        /// checks if receiver is effectively ldarg.0
        /// </summary>
        private bool IsThisReceiver(BoundExpression receiver)
        {
            switch (receiver.Kind)
            {
                case BoundKind.ThisReference:
                    return true;

                case BoundKind.Sequence:
                    var seqValue = ((BoundSequence)(receiver)).Value;
                    return IsThisReceiver(seqValue);
            }

            return false;
        }

        private enum CallKind
        {
            Call,
            CallVirt,
            ConstrainedCallVirt,
        }

1454
        private void EmitCallExpression(BoundCall call, UseKind useKind)
P
Pilchie 已提交
1455 1456 1457 1458 1459 1460
        {
            var method = call.Method;
            var receiver = call.ReceiverOpt;
            LocalDefinition tempOpt = null;

            // Calls to the default struct constructor are emitted as initobj, rather than call.
1461
            // NOTE: constructor invocations are represented as BoundObjectCreationExpressions,
P
Pilchie 已提交
1462 1463
            // rather than BoundCalls.  This is why we can be confident that if we see a call to a
            // constructor, it has this very specific form.
1464
            if (method.IsDefaultValueTypeConstructor())
P
Pilchie 已提交
1465 1466
            {
                Debug.Assert(method.IsImplicitlyDeclared);
1467
                Debug.Assert(TypeSymbol.Equals(method.ContainingType, receiver.Type, TypeCompareKind.ConsiderEverything2));
P
Pilchie 已提交
1468 1469
                Debug.Assert(receiver.Kind == BoundKind.ThisReference);

1470
                tempOpt = EmitReceiverRef(receiver, AddressKind.Writeable);
1471
                _builder.EmitOpCode(ILOpCode.Initobj);    //  initobj  <MyStruct>
P
Pilchie 已提交
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
                EmitSymbolToken(method.ContainingType, call.Syntax);
                FreeOptTemp(tempOpt);

                return;
            }

            var arguments = call.Arguments;

            CallKind callKind;

1482
            if (!method.RequiresInstanceReceiver)
P
Pilchie 已提交
1483 1484 1485 1486 1487 1488 1489 1490 1491
            {
                callKind = CallKind.Call;
            }
            else
            {
                var receiverType = receiver.Type;

                if (receiverType.IsVerifierReference())
                {
1492
                    EmitExpression(receiver, used: true);
P
Pilchie 已提交
1493

1494 1495 1496
                    // In some cases CanUseCallOnRefTypeReceiver returns true which means that 
                    // null check is unnecessary and we can use "call"
                    if (receiver.SuppressVirtualCalls ||
P
Pilchie 已提交
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
                        (!method.IsMetadataVirtual() && CanUseCallOnRefTypeReceiver(receiver)))
                    {
                        callKind = CallKind.Call;
                    }
                    else
                    {
                        callKind = CallKind.CallVirt;
                    }
                }
                else if (receiverType.IsVerifierValue())
                {
                    NamedTypeSymbol methodContainingType = method.ContainingType;
V
vsadov 已提交
1509
                    if (methodContainingType.IsVerifierValue())
P
Pilchie 已提交
1510
                    {
V
vsadov 已提交
1511 1512
                        // if method is defined in the struct itself it is assumed to be mutating, unless 
                        // it is a member of a readonly struct and is not a constructor
V
vsadov 已提交
1513
                        var receiverAddresskind = IsReadOnlyCall(method, methodContainingType) ?
V
vsadov 已提交
1514 1515 1516 1517 1518 1519 1520
                                                                        AddressKind.ReadOnly :
                                                                        AddressKind.Writeable;
                        if (MayUseCallForStructMethod(method))
                        {
                            // NOTE: this should be either a method which overrides some abstract method or 
                            //       does not override anything (with few exceptions, see MayUseCallForStructMethod); 
                            //       otherwise we should not use direct 'call' and must use constrained call;
P
Pilchie 已提交
1521

V
vsadov 已提交
1522
                            // calling a method defined in a value type
1523
                            Debug.Assert(TypeSymbol.Equals(receiverType, methodContainingType, TypeCompareKind.ObliviousNullableModifierMatchesAny));
V
vsadov 已提交
1524
                            tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
V
vsadov 已提交
1525 1526 1527 1528
                            callKind = CallKind.Call;
                        }
                        else
                        {
V
vsadov 已提交
1529
                            tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
V
vsadov 已提交
1530 1531
                            callKind = CallKind.ConstrainedCallVirt;
                        }
P
Pilchie 已提交
1532 1533 1534
                    }
                    else
                    {
V
vsadov 已提交
1535 1536 1537 1538
                        // calling a method defined in a base class.

                        // When calling a method that is virtual in metadata on a struct receiver, 
                        // we use a constrained virtual call. If possible, it will skip boxing.
P
Pilchie 已提交
1539 1540
                        if (method.IsMetadataVirtual())
                        {
1541
                            // NB: all methods that a struct could inherit from bases are non-mutating
1542 1543
                            //     treat receiver as ReadOnly
                            tempOpt = EmitReceiverRef(receiver, AddressKind.ReadOnly);
P
Pilchie 已提交
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
                            callKind = CallKind.ConstrainedCallVirt;
                        }
                        else
                        {
                            EmitExpression(receiver, used: true);
                            EmitBox(receiverType, receiver.Syntax);
                            callKind = CallKind.Call;
                        }
                    }
                }
                else
                {
                    // receiver is generic and method must come from the base or an interface or a generic constraint
                    // if the receiver is actually a value type it would need to be boxed.
                    // let .constrained sort this out. 
1559
                    callKind = receiverType.IsReferenceType && !IsRef(receiver) ?
P
Pilchie 已提交
1560 1561 1562
                                CallKind.CallVirt :
                                CallKind.ConstrainedCallVirt;

1563
                    tempOpt = EmitReceiverRef(receiver, callKind == CallKind.ConstrainedCallVirt ? AddressKind.Constrained : AddressKind.Writeable);
P
Pilchie 已提交
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
                }
            }

            // When emitting a callvirt to a virtual method we always emit the method info of the
            // method that first declared the virtual method, not the method info of an
            // overriding method. It would be a subtle breaking change to change that rule;
            // see bug 6156 for details.

            MethodSymbol actualMethodTargetedByTheCall = method;
            if (method.IsOverride && callKind != CallKind.Call)
            {
1575
                actualMethodTargetedByTheCall = method.GetConstructedLeastOverriddenMethod(_method.ContainingType);
P
Pilchie 已提交
1576 1577 1578 1579
            }

            if (callKind == CallKind.ConstrainedCallVirt && actualMethodTargetedByTheCall.ContainingType.IsValueType)
            {
C
Charles Stoner 已提交
1580
                // special case for overridden methods like ToString(...) called on
P
Pilchie 已提交
1581 1582 1583 1584 1585 1586 1587 1588 1589
                // value types: if the original method used in emit cannot use callvirt in this
                // case, change it to Call.
                callKind = CallKind.Call;
            }

            // Devirtualizing of calls to effectively sealed methods.
            if (callKind == CallKind.CallVirt)
            {
                // NOTE: we check that we call method in same module just to be sure
C
Charles Stoner 已提交
1590
                // that it cannot be recompiled as not final and make our call not verifiable. 
P
Pilchie 已提交
1591 1592 1593 1594 1595
                // such change by adversarial user would arguably be a compat break, but better be safe...
                // In reality we would typically have one method calling another method in the same class (one GetEnumerator calling another).
                // Other scenarios are uncommon since base class cannot be sealed and 
                // referring to a derived type in a different module is not an easy thing to do.
                if (IsThisReceiver(receiver) && actualMethodTargetedByTheCall.ContainingType.IsSealed &&
1596
                        (object)actualMethodTargetedByTheCall.ContainingModule == (object)_method.ContainingModule)
P
Pilchie 已提交
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
                {
                    // special case for target is in a sealed class and "this" receiver.
                    Debug.Assert(receiver.Type.IsVerifierReference());
                    callKind = CallKind.Call;
                }

                // NOTE: we do not check that we call method in same module.
                // Because of the "GetOriginalConstructedOverriddenMethod" above, the actual target
                // can only be final when it is "newslot virtual final".
                // In such case Dev11 emits "call" and we will just replicate the behavior. (see DevDiv: 546853 )
1607
                else if (actualMethodTargetedByTheCall.IsMetadataFinal && CanUseCallOnRefTypeReceiver(receiver))
P
Pilchie 已提交
1608 1609 1610 1611 1612 1613 1614
                {
                    // special case for calling 'final' virtual method on reference receiver
                    Debug.Assert(receiver.Type.IsVerifierReference());
                    callKind = CallKind.Call;
                }
            }

1615
            EmitArguments(arguments, method.Parameters, call.ArgumentRefKindsOpt);
P
Pilchie 已提交
1616 1617 1618 1619
            int stackBehavior = GetCallStackBehavior(call);
            switch (callKind)
            {
                case CallKind.Call:
1620
                    _builder.EmitOpCode(ILOpCode.Call, stackBehavior);
P
Pilchie 已提交
1621 1622 1623
                    break;

                case CallKind.CallVirt:
1624
                    _builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
P
Pilchie 已提交
1625 1626 1627
                    break;

                case CallKind.ConstrainedCallVirt:
1628
                    _builder.EmitOpCode(ILOpCode.Constrained);
P
Pilchie 已提交
1629
                    EmitSymbolToken(receiver.Type, receiver.Syntax);
1630
                    _builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
P
Pilchie 已提交
1631 1632 1633 1634 1635 1636 1637 1638
                    break;
            }

            EmitSymbolToken(actualMethodTargetedByTheCall, call.Syntax,
                            actualMethodTargetedByTheCall.IsVararg ? (BoundArgListOperator)call.Arguments[call.Arguments.Length - 1] : null);

            if (!method.ReturnsVoid)
            {
1639
                EmitPopIfUnused(useKind != UseKind.Unused);
P
Pilchie 已提交
1640
            }
V
vsadov 已提交
1641
            else if (_ilEmitStyle == ILEmitStyle.Debug)
P
Pilchie 已提交
1642 1643 1644
            {
                // The only void methods with usable return values are constructors and we represent those
                // as BoundObjectCreationExpressions, not BoundCalls.
1645
                Debug.Assert(useKind == UseKind.Unused, "Using the return value of a void method.");
1646
                Debug.Assert(_method.GenerateDebugInfo, "Implied by this.emitSequencePoints");
P
Pilchie 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675

                // DevDiv #15135.  When a method like System.Diagnostics.Debugger.Break() is called, the
                // debugger sees an event indicating that a user break (vs a breakpoint) has occurred.
                // When this happens, it uses ICorDebugILFrame.GetIP(out uint, out CorDebugMappingResult)
                // to determine the current instruction pointer.  This method returns the instruction
                // *after* the call.  The source location is then given by the last sequence point before
                // or on this instruction.  As a result, if the instruction after the call has its own
                // sequence point, then that sequence point will be used to determine the source location
                // and the debugging experience will be disrupted.  The easiest way to ensure that the next
                // instruction does not have a sequence point is to insert a nop.  Obviously, we only do this
                // if debugging is enabled and optimization is disabled.

                // From ILGENREC::genCall:
                //   We want to generate a NOP after CALL opcodes that end a statement so the debugger
                //   has better stepping behavior

                // CONSIDER: In the native compiler, there's an additional restriction on when this nop is
                // inserted.  It is quite complicated, but it basically seems to say that, if we thought
                // we could omit the temp-and-copy for a struct construction and it turned out that we
                // couldn't (perhaps because the assigned local was captured by a lambda), and if we're
                // not using the result of the constructor call (how can this even happen?), then we don't
                // want to insert the nop.  Since the consequence of not implementing this complicated logic
                // is an extra nop in debug code, this is likely not a priority.

                // CONSIDER: The native compiler also checks !(tree->flags & EXF_NODEBUGINFO).  We don't have
                // this mutable bit on our bound nodes, so we can't exactly match the behavior.  We might be
                // able to approximate the native behavior by inspecting call.WasCompilerGenerated, but it is
                // not in a reliable state after lowering.

1676
                _builder.EmitOpCode(ILOpCode.Nop);
P
Pilchie 已提交
1677 1678
            }

1679 1680
            if (useKind == UseKind.UsedAsValue && method.RefKind != RefKind.None)
            {
1681
                EmitLoadIndirect(method.ReturnType, call.Syntax);
1682 1683 1684 1685 1686 1687
            }
            else if (useKind == UseKind.UsedAsAddress)
            {
                Debug.Assert(method.RefKind != RefKind.None);
            }

P
Pilchie 已提交
1688 1689 1690
            FreeOptTemp(tempOpt);
        }

V
vsadov 已提交
1691 1692 1693 1694
        private bool IsReadOnlyCall(MethodSymbol method, NamedTypeSymbol methodContainingType)
        {
            Debug.Assert(methodContainingType.IsVerifierValue(), "only struct calls can be readonly");

1695
            if (method.IsEffectivelyReadOnly && method.MethodKind != MethodKind.Constructor)
V
vsadov 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
            {
                return true;
            }

            if (methodContainingType.IsNullableType())
            {
                var originalMethod = method.OriginalDefinition;

                if ((object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_GetValueOrDefault) ||
                    (object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value) ||
                    (object)originalMethod == this._module.Compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_HasValue))
                {
                    return true;
                }
            }

            return false;
        }

1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
        // returns true when receiver is already a ref.
        // in such cases calling through a ref could be preferred over 
        // calling through indirectly loaded value.
        private bool IsRef(BoundExpression receiver)
        {
            switch (receiver.Kind)
            {
                case BoundKind.Local:
                    return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;

                case BoundKind.Parameter:
                    return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;

1728 1729 1730
                case BoundKind.Call:
                    return ((BoundCall)receiver).Method.RefKind != RefKind.None;

1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
                case BoundKind.Dup:
                    return ((BoundDup)receiver).RefKind != RefKind.None;

                case BoundKind.Sequence:
                    return IsRef(((BoundSequence)receiver).Value);
            }

            return false;
        }

P
Pilchie 已提交
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
        private static int GetCallStackBehavior(BoundCall call)
        {
            int stack = 0;

            if (!call.Method.ReturnsVoid)
            {
                // The call puts the return value on the stack.
                stack += 1;
            }

1751
            if (call.Method.RequiresInstanceReceiver)
P
Pilchie 已提交
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
            {
                // The call pops the receiver off the stack.
                stack -= 1;
            }

            if (call.Method.IsVararg)
            {
                // The call pops all the arguments, fixed and variadic.
                int fixedArgCount = call.Arguments.Length - 1;
                int varArgCount = ((BoundArgListOperator)call.Arguments[fixedArgCount]).Arguments.Length;
                stack -= fixedArgCount;
                stack -= varArgCount;
            }
            else
            {
                // The call pops all the arguments.
                stack -= call.Arguments.Length;
            }

            return stack;
        }

        private static int GetObjCreationStackBehavior(BoundObjectCreationExpression objCreation)
        {
            int stack = 0;

            // Constructor puts the return value on the stack.
            stack += 1;

            if (objCreation.Constructor.IsVararg)
            {
                // Constructor pops all the arguments, fixed and variadic.
                int fixedArgCount = objCreation.Arguments.Length - 1;
                int varArgCount = ((BoundArgListOperator)objCreation.Arguments[fixedArgCount]).Arguments.Length;
                stack -= fixedArgCount;
                stack -= varArgCount;
            }
            else
            {
                // Constructor pops all the arguments.
                stack -= objCreation.Arguments.Length;
            }

            return stack;
        }

        /// <summary>
        /// Used to decide if we need to emit 'call' or 'callvirt' for structure method.
        /// It basically checks if the method overrides any other and method's defining type
        /// is not a 'special' or 'special-by-ref' type. 
        /// </summary>
1803
        internal static bool MayUseCallForStructMethod(MethodSymbol method)
P
Pilchie 已提交
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
        {
            Debug.Assert(method.ContainingType.IsVerifierValue(), "this is not a value type");

            if (!method.IsMetadataVirtual())
            {
                return true;
            }

            var overriddenMethod = method.OverriddenMethod;
            if ((object)overriddenMethod == null || overriddenMethod.IsAbstract)
            {
                return true;
            }

            var containingType = method.ContainingType;
C
Charles Stoner 已提交
1819 1820
            // overrides in structs that are special types can be called directly.
            // we can assume that special types will not be removing overrides
1821
            return containingType.SpecialType != SpecialType.None;
P
Pilchie 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
        }

        /// <summary>
        /// When array operation get long or ulong arguments the args should be 
        /// cast to native int.
        /// Note that the cast is always checked.
        /// </summary>
        private void TreatLongsAsNative(Microsoft.Cci.PrimitiveTypeCode tc)
        {
            if (tc == Microsoft.Cci.PrimitiveTypeCode.Int64)
            {
1833
                _builder.EmitOpCode(ILOpCode.Conv_ovf_i);
P
Pilchie 已提交
1834 1835 1836
            }
            else if (tc == Microsoft.Cci.PrimitiveTypeCode.UInt64)
            {
1837
                _builder.EmitOpCode(ILOpCode.Conv_ovf_i_un);
P
Pilchie 已提交
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
            }
        }

        private void EmitArrayLength(BoundArrayLength expression, bool used)
        {
            // The binder recognizes Array.Length and Array.LongLength and creates BoundArrayLength for them.
            // 
            // ArrayLength can be either 
            //      int32 for Array.Length
            //      int64 for Array.LongLength
            //      UIntPtr for synthetic code that needs just check if length != 0 - 
            //                  this is used in "fixed(int* ptr = arr)"
            Debug.Assert(expression.Type.SpecialType == SpecialType.System_Int32 ||
                expression.Type.SpecialType == SpecialType.System_Int64 ||
                expression.Type.SpecialType == SpecialType.System_UIntPtr);

            // ldlen will null-check the expression so it must be "used"
            EmitExpression(expression.Expression, used: true);
1856
            _builder.EmitOpCode(ILOpCode.Ldlen);
P
Pilchie 已提交
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869

            var typeTo = expression.Type.PrimitiveTypeCode;

            // NOTE: ldlen returns native uint, but newarr takes native int, so the length value is always 
            //       a positive native int. We can treat it as either signed or unsigned.
            //       We will use whatever typeTo says so we do not need to convert because of sign.
            var typeFrom = typeTo.IsUnsigned() ? Microsoft.Cci.PrimitiveTypeCode.UIntPtr : Microsoft.Cci.PrimitiveTypeCode.IntPtr;

            // NOTE: In Dev10 C# this cast is unchecked.
            // That seems to be wrong since that would cause silent truncation on 64bit platform if that implements large arrays. 
            // 
            // Emitting checked conversion however results in redundant overflow checks on 64bit and also inhibits range check hoisting in loops.
            // Therefore we will emit unchecked conversion here as C# compiler always did.
1870
            _builder.EmitNumericConversion(typeFrom, typeTo, @checked: false);
P
Pilchie 已提交
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880

            EmitPopIfUnused(used);
        }

        private void EmitArrayCreationExpression(BoundArrayCreation expression, bool used)
        {
            var arrayType = (ArrayTypeSymbol)expression.Type;

            EmitArrayIndices(expression.Bounds);

1881
            if (arrayType.IsSZArray)
P
Pilchie 已提交
1882
            {
1883
                _builder.EmitOpCode(ILOpCode.Newarr);
1884
                EmitSymbolToken(arrayType.ElementType, expression.Syntax);
P
Pilchie 已提交
1885 1886 1887
            }
            else
            {
1888
                _builder.EmitArrayCreation(Emit.PEModuleBuilder.Translate(arrayType), expression.Syntax, _diagnostics);
P
Pilchie 已提交
1889 1890 1891 1892 1893 1894 1895
            }

            if (expression.InitializerOpt != null)
            {
                EmitArrayInitializers(arrayType, expression.InitializerOpt);
            }

1896
            // newarr has side-effects (negative bounds etc) so always emitted.
P
Pilchie 已提交
1897 1898 1899
            EmitPopIfUnused(used);
        }

1900
        private void EmitConvertedStackAllocExpression(BoundConvertedStackAllocExpression expression, bool used)
P
Pilchie 已提交
1901
        {
V
vsadov 已提交
1902 1903
            EmitExpression(expression.Count, used);

C
Charles Stoner 已提交
1904
            // the only sideeffect of a localloc is a nondeterministic and generally fatal StackOverflow.
V
vsadov 已提交
1905 1906 1907
            // we can ignore that if the actual result is unused
            if (used)
            {
A
Andy Gocke 已提交
1908
                _sawStackalloc = true;
V
vsadov 已提交
1909 1910
                _builder.EmitOpCode(ILOpCode.Localloc);
            }
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927

            var initializer = expression.InitializerOpt;
            if (initializer != null)
            {
                if (used)
                {
                    EmitStackAllocInitializers(expression.Type, initializer);
                }
                else
                {
                    // If not used, just emit initializer elements to preserve possible sideeffects
                    foreach (var init in initializer.Initializers)
                    {
                        EmitExpression(init, used: false);
                    }
                }
            }
P
Pilchie 已提交
1928 1929 1930 1931 1932
        }

        private void EmitObjectCreationExpression(BoundObjectCreationExpression expression, bool used)
        {
            MethodSymbol constructor = expression.Constructor;
1933
            if (constructor.IsDefaultValueTypeConstructor())
P
Pilchie 已提交
1934 1935 1936 1937 1938
            {
                EmitInitObj(expression.Type, used, expression.Syntax);
            }
            else
            {
1939
                // check if need to construct at all
1940
                if (!used && ConstructorNotSideEffecting(constructor))
1941
                {
1942
                    // ctor has no side-effects, so we will just evaluate the arguments
1943 1944 1945 1946
                    foreach (var arg in expression.Arguments)
                    {
                        EmitExpression(arg, used: false);
                    }
1947 1948

                    return;
1949
                }
1950 1951 1952 1953

                // ReadOnlySpan may just refer to the blob, if possible.
                if (this._module.Compilation.IsReadOnlySpanType(expression.Type) &&
                    expression.Arguments.Length == 1)
1954
                {
1955 1956 1957 1958 1959
                    if (TryEmitReadonlySpanAsBlobWrapper((NamedTypeSymbol)expression.Type, expression.Arguments[0], used, inPlace: false))
                    {
                        return;
                    }
                }
P
Pilchie 已提交
1960

1961 1962
                // none of the above cases, so just create an instance
                EmitArguments(expression.Arguments, constructor.Parameters, expression.ArgumentRefKindsOpt);
P
Pilchie 已提交
1963

1964 1965
                var stackAdjustment = GetObjCreationStackBehavior(expression);
                _builder.EmitOpCode(ILOpCode.Newobj, stackAdjustment);
P
Pilchie 已提交
1966

1967 1968 1969 1970 1971
                // for variadic ctors emit expanded ctor token
                EmitSymbolToken(constructor, expression.Syntax,
                                constructor.IsVararg ? (BoundArgListOperator)expression.Arguments[expression.Arguments.Length - 1] : null);

                EmitPopIfUnused(used);
P
Pilchie 已提交
1972 1973 1974
            }
        }

1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
        /// <summary>
        /// Recognizes constructors known to not have side-effects (which means they can be skipped unless the constructed object is used)
        /// </summary>
        private bool ConstructorNotSideEffecting(MethodSymbol constructor)
        {
            var originalDef = constructor.OriginalDefinition;
            var compilation = _module.Compilation;

            if (originalDef == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor))
            {
                return true;
            }

1988
            if (originalDef.ContainingType.Name == NamedTypeSymbol.ValueTupleTypeName &&
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
                    (originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__ctor)))
            {
                return true;
            }

            return false;
        }

2004
        private void EmitAssignmentExpression(BoundAssignmentOperator assignmentOperator, UseKind useKind)
P
Pilchie 已提交
2005
        {
2006
            if (TryEmitAssignmentInPlace(assignmentOperator, useKind != UseKind.Unused))
P
Pilchie 已提交
2007
            {
2008
                Debug.Assert(!assignmentOperator.IsRef);
P
Pilchie 已提交
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
                return;
            }

            // Assignment expression codegen has the following parts:
            //
            // * PreRHS: We need to emit instructions before the load of the right hand side if:
            //   - If the left hand side is a ref local or ref formal parameter and the right hand 
            //     side is a value then we must put the ref on the stack early so that we can store 
            //     indirectly into it.
            //   - If the left hand side is an array slot then we must evaluate the array and indices
            //     before we evaluate the right hand side. We ensure that the array and indices are 
            //     on the stack when the store is executed.
            //   - Similarly, if the left hand side is a non-static field then its receiver must be
            //     evaluated before the right hand side.
            //
            // * RHS: There are three possible ways to do an assignment with respect to "refness", 
            //   and all are found in the lowering of:
            //
            //   N().s += 10;
            //
            //   That expression is realized as 
            //
            //   ref int addr = ref N().s;   // Assign a ref on the right hand side to the left hand side.
            //   int sum = addr + 10;        // No refs at all; assign directly to sum.
            //   addr = sum;                 // Assigns indirectly through the address.
            //
            //   - If we are in the first case then assignmentOperator.RefKind is Ref and the left hand side is a 
            //     ref local temporary. We simply assign the ref on the RHS to the storage on the LHS with no indirection.
            //
            //   - If we are in the second case then nothing is ref; we have a value on one side an a local on the other.
            //     Again, there is no indirection.
            // 
            //   - If we are in the third case then we have a ref on the left and a value on the right. We must compute the
            //     value of the right hand side and then store it into the left hand side.
            //
            // * Duplication: The result of an assignment operation is the value that was assigned. It is possible that 
            //   later codegen is expecting this value to be on the stack when we're done here. This is controlled by
            //   the "used" formal parameter. There are two possible cases:
            //   - If the preamble put stuff on the stack for the usage of the store, then we must not put an extra copy
            //     of the right hand side value on the stack; that will be between the value and the stuff needed to 
            //     do the storage. In that case we put the right hand side value in a temporary and restore it later.
            //   - Otherwise we can just do a dup instruction; there's nothing before the dup on the stack that we'll need.
            // 
            // * Storage: Either direct or indirect, depending. See the RHS section above for details.
            // 
            // * Post-storage: If we stashed away the duplicated value in the temporary, we need to restore it back to the stack.

            bool lhsUsesStack = EmitAssignmentPreamble(assignmentOperator);
            EmitAssignmentValue(assignmentOperator);
2058
            LocalDefinition temp = EmitAssignmentDuplication(assignmentOperator, useKind, lhsUsesStack);
P
Pilchie 已提交
2059
            EmitStore(assignmentOperator);
2060
            EmitAssignmentPostfix(assignmentOperator, temp, useKind);
P
Pilchie 已提交
2061 2062 2063 2064 2065 2066 2067 2068
        }

        // sometimes it is possible and advantageous to get an address of the lHS and 
        // perform assignment as an in-place initialization via initobj or constructor invocation.
        //
        // 1) initobj 
        //    is used when assigning default value to T that is not a verifier reference.
        //
2069
        // 2) in-place ctor call 
P
Pilchie 已提交
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
        //    is used when assigning a freshly created struct. "x = new S(arg)" can be
        //    replaced by x.S(arg) as long as partial assignment cannot be observed -
        //    i.e. target must not be on the heap and we should not be in a try block.
        private bool TryEmitAssignmentInPlace(BoundAssignmentOperator assignmentOperator, bool used)
        {
            var left = assignmentOperator.Left;

            // if result is used, and lives on heap, we must keep RHS value on the stack.
            // otherwise we can try conjuring up the RHS value directly where it belongs.
            if (used && !TargetIsNotOnHeap(left))
            {
                return false;
            }

            if (!SafeToGetWriteableReference(left))
            {
                // cannot take a ref
                return false;
            }

            var right = assignmentOperator.Right;
            var rightType = right.Type;

            // in-place is not advantageous for reference types or constants
            if (!rightType.IsTypeParameter())
            {
                if (rightType.IsReferenceType || (right.ConstantValue != null && rightType.SpecialType != SpecialType.System_Decimal))
                {
                    return false;
                }
            }

            if (right.IsDefaultValue())
            {
                InPlaceInit(left, used);
                return true;
            }

2108
            if (right is BoundObjectCreationExpression objCreation)
P
Pilchie 已提交
2109
            {
2110 2111 2112 2113 2114 2115 2116 2117
                // If we are creating a Span<T> from a stackalloc, which is a particular pattern of code
                // produced by lowering, we must use the constructor in its standard form because the stack
                // is required to contain nothing more than stackalloc's argument.
                if (objCreation.Arguments.Length > 0 && objCreation.Arguments[0].Kind == BoundKind.ConvertedStackAllocExpression)
                {
                    return false;
                }

P
Pilchie 已提交
2118
                // It is desirable to do in-place ctor call if possible.
2119
                // we could do newobj/stloc, but in-place call 
2120
                // produces the same or better code in current JITs 
P
Pilchie 已提交
2121 2122
                if (PartialCtorResultCannotEscape(left))
                {
2123 2124 2125 2126 2127 2128 2129 2130 2131
                    var ctor = objCreation.Constructor;

                    // ctor can possibly see its own assignments indirectly if there are ref parameters or __arglist
                    if (System.Linq.ImmutableArrayExtensions.All(ctor.Parameters, p => p.RefKind == RefKind.None) &&
                        !ctor.IsVararg)
                    {
                        InPlaceCtorCall(left, objCreation, used);
                        return true;
                    }
P
Pilchie 已提交
2132 2133 2134 2135 2136 2137 2138 2139
                }
            }

            return false;
        }

        private bool SafeToGetWriteableReference(BoundExpression left)
        {
2140
            if (!HasHome(left, AddressKind.Writeable))
P
Pilchie 已提交
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
            {
                return false;
            }

            // because of array covariance, taking a reference to an element of 
            // generic array may fail even though assignment "arr[i] = default(T)" would always succeed.
            if (left.Kind == BoundKind.ArrayAccess && left.Type.TypeKind == TypeKind.TypeParameter && !left.Type.IsValueType)
            {
                return false;
            }

            if (left.Kind == BoundKind.FieldAccess)
            {
                var fieldAccess = (BoundFieldAccess)left;
                if (fieldAccess.FieldSymbol.IsVolatile ||
2156
                    DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
P
Pilchie 已提交
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
                {
                    return false;
                }
            }

            return true;
        }

        private void InPlaceInit(BoundExpression target, bool used)
        {
2167
            var temp = EmitAddress(target, AddressKind.Writeable);
2168
            Debug.Assert(temp == null, "in-place init target should not create temps");
2169

V
vsadov 已提交
2170
            _builder.EmitOpCode(ILOpCode.Initobj);    //  initobj  <MyStruct>
P
Pilchie 已提交
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
            EmitSymbolToken(target.Type, target.Syntax);

            if (used)
            {
                Debug.Assert(TargetIsNotOnHeap(target), "cannot read-back the target since it could have been modified");
                EmitExpression(target, used);
            }
        }

        private void InPlaceCtorCall(BoundExpression target, BoundObjectCreationExpression objCreation, bool used)
        {
2182 2183
            Debug.Assert(TargetIsNotOnHeap(target), "in-place construction target should not be on heap");

2184
            var temp = EmitAddress(target, AddressKind.Writeable);
2185
            Debug.Assert(temp == null, "in-place ctor target should not create temps");
P
Pilchie 已提交
2186

2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
            // ReadOnlySpan may just refer to the blob, if possible.
            if (this._module.Compilation.IsReadOnlySpanType(objCreation.Type) && objCreation.Arguments.Length == 1)
            {
                if (TryEmitReadonlySpanAsBlobWrapper((NamedTypeSymbol)objCreation.Type, objCreation.Arguments[0], used, inPlace: true))
                {
                    if (used)
                    {
                        EmitExpression(target, used: true);
                    }
                    return;
                }
            }

P
Pilchie 已提交
2200
            var constructor = objCreation.Constructor;
2201
            EmitArguments(objCreation.Arguments, constructor.Parameters, objCreation.ArgumentRefKindsOpt);
P
Pilchie 已提交
2202 2203
            // -2 to adjust for consumed target address and not produced value.
            var stackAdjustment = GetObjCreationStackBehavior(objCreation) - 2;
2204
            _builder.EmitOpCode(ILOpCode.Call, stackAdjustment);
P
Pilchie 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
            // for variadic ctors emit expanded ctor token
            EmitSymbolToken(constructor, objCreation.Syntax,
                            constructor.IsVararg ? (BoundArgListOperator)objCreation.Arguments[objCreation.Arguments.Length - 1] : null);

            if (used)
            {
                EmitExpression(target, used: true);
            }
        }

        // partial ctor results are not observable when target is not on the heap.
        // we also must not be in a try, otherwise if ctor throws
        // partially assigned value may be observed in the handler.
        private bool PartialCtorResultCannotEscape(BoundExpression left)
        {
            if (TargetIsNotOnHeap(left))
            {
2222
                if (_tryNestingLevel != 0)
P
Pilchie 已提交
2223 2224
                {
                    var local = left as BoundLocal;
2225
                    if (local != null && !_builder.PossiblyDefinedOutsideOfTry(GetLocal(local)))
P
Pilchie 已提交
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
                    {
                        // local defined inside immediate Try - cannot escape
                        return true;
                    }

                    // local defined outside of immediate try or it is a parameter - can escape
                    return false;
                }

                // we are not in a try - locals, parameters cannot escape
                return true;
            }

            // left is a reference, partial initializations can escape.
            return false;
        }

        // returns True when assignment target is definitely not on the heap
        private static bool TargetIsNotOnHeap(BoundExpression left)
        {
            switch (left.Kind)
            {
                case BoundKind.Parameter:
                    return ((BoundParameter)left).ParameterSymbol.RefKind == RefKind.None;

                case BoundKind.Local:
                    // NOTE: stack locals are either homeless or refs, no need to special case them
                    //       they will never be assigned in-place.
                    return ((BoundLocal)left).LocalSymbol.RefKind == RefKind.None;
            }

            return false;
        }


        private bool EmitAssignmentPreamble(BoundAssignmentOperator assignmentOperator)
        {
2263
            var assignmentTarget = assignmentOperator.Left;
P
Pilchie 已提交
2264 2265
            bool lhsUsesStack = false;

2266
            switch (assignmentTarget.Kind)
P
Pilchie 已提交
2267 2268
            {
                case BoundKind.RefValueOperator:
2269
                    EmitRefValueAddress((BoundRefValueOperator)assignmentTarget);
P
Pilchie 已提交
2270 2271 2272 2273
                    break;

                case BoundKind.FieldAccess:
                    {
2274
                        var left = (BoundFieldAccess)assignmentTarget;
P
Pilchie 已提交
2275 2276
                        if (!left.FieldSymbol.IsStatic)
                        {
2277
                            var temp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
P
Pilchie 已提交
2278 2279 2280 2281 2282 2283 2284 2285
                            Debug.Assert(temp == null, "temp is unexpected when assigning to a field");
                            lhsUsesStack = true;
                        }
                    }
                    break;

                case BoundKind.Parameter:
                    {
2286
                        var left = (BoundParameter)assignmentTarget;
2287
                        if (left.ParameterSymbol.RefKind != RefKind.None &&
2288
                            !assignmentOperator.IsRef)
P
Pilchie 已提交
2289
                        {
2290
                            _builder.EmitLoadArgumentOpcode(ParameterSlot(left));
P
Pilchie 已提交
2291 2292 2293 2294 2295 2296 2297
                            lhsUsesStack = true;
                        }
                    }
                    break;

                case BoundKind.Local:
                    {
2298
                        var left = (BoundLocal)assignmentTarget;
P
Pilchie 已提交
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318

                        // Again, consider our earlier case:
                        //
                        // ref int addr = ref N().s;
                        // int sum = addr + 10; 
                        // addr = sum;
                        //
                        // There are three different ways we could be assigning to a local.
                        //
                        // In the first case, we want to simply call N(), take the address
                        // of s, and then store that address in addr.
                        //
                        // In the second case again we simply want to compute the sum and
                        // store the result in sum.
                        //
                        // In the third case however we want to first load the contents of
                        // addr -- the address of field s -- then put the sum on the stack,
                        // and then do an indirect store. In that case we need to have the
                        // contents of addr on the stack.

2319
                        if (left.LocalSymbol.RefKind != RefKind.None && !assignmentOperator.IsRef)
P
Pilchie 已提交
2320 2321 2322 2323
                        {
                            if (!IsStackLocal(left.LocalSymbol))
                            {
                                LocalDefinition localDefinition = GetLocal(left);
2324
                                _builder.EmitLocalLoad(localDefinition);
P
Pilchie 已提交
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
                            }
                            else
                            {
                                // this is a case of indirect assignment to a stack temp.
                                // currently byref temp can only be a stack local in scenarios where 
                                // there is only one assignment and it is the last one. 
                                // I do not yet know how to support cases where we assign more than once. 
                                // That where Dup of LHS would be needed, but as a general scenario 
                                // it is not always possible to handle. Fortunately all the cases where we
                                // indirectly assign to a byref temp come from rewriter and all
                                // they all are write-once cases.
                                //
                                // For now analyzer asserts that indirect writes are final reads of 
                                // a ref local. And we never need a dup here.

                                // builder.EmitOpCode(ILOpCode.Dup);
                            }

                            lhsUsesStack = true;
                        }
                    }
                    break;

                case BoundKind.ArrayAccess:
                    {
2350
                        var left = (BoundArrayAccess)assignmentTarget;
P
Pilchie 已提交
2351 2352 2353 2354 2355 2356 2357 2358
                        EmitExpression(left.Expression, used: true);
                        EmitArrayIndices(left.Indices);
                        lhsUsesStack = true;
                    }
                    break;

                case BoundKind.ThisReference:
                    {
2359
                        var left = (BoundThisReference)assignmentTarget;
P
Pilchie 已提交
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369

                        var temp = EmitAddress(left, AddressKind.Writeable);
                        Debug.Assert(temp == null, "taking ref of this should not create a temp");

                        lhsUsesStack = true;
                    }
                    break;

                case BoundKind.Dup:
                    {
2370
                        var left = (BoundDup)assignmentTarget;
P
Pilchie 已提交
2371 2372 2373 2374 2375 2376 2377 2378

                        var temp = EmitAddress(left, AddressKind.Writeable);
                        Debug.Assert(temp == null, "taking ref of Dup should not create a temp");

                        lhsUsesStack = true;
                    }
                    break;

2379 2380 2381
                case BoundKind.ConditionalOperator:
                    {
                        var left = (BoundConditionalOperator)assignmentTarget;
2382
                        Debug.Assert(left.IsRef);
2383 2384 2385 2386 2387 2388 2389 2390

                        var temp = EmitAddress(left, AddressKind.Writeable);
                        Debug.Assert(temp == null, "taking ref of this should not create a temp");

                        lhsUsesStack = true;
                    }
                    break;

P
Pilchie 已提交
2391 2392
                case BoundKind.PointerIndirectionOperator:
                    {
2393
                        var left = (BoundPointerIndirectionOperator)assignmentTarget;
P
Pilchie 已提交
2394 2395 2396 2397 2398 2399 2400

                        EmitExpression(left.Operand, used: true);

                        lhsUsesStack = true;
                    }
                    break;

2401 2402
                case BoundKind.Sequence:
                    {
2403
                        var sequence = (BoundSequence)assignmentTarget;
2404

2405 2406 2407
                        // NOTE: not releasing sequence locals right away. 
                        // Since sequence is used as a variable, we will keep the locals for the extent of the containing expression
                        DefineAndRecordLocals(sequence);
2408
                        EmitSideEffects(sequence);
2409
                        lhsUsesStack = EmitAssignmentPreamble(assignmentOperator.Update(sequence.Value, assignmentOperator.Right, assignmentOperator.IsRef, assignmentOperator.Type));
2410
                        CloseScopeAndKeepLocals(sequence);
2411 2412 2413
                    }
                    break;

2414 2415
                case BoundKind.Call:
                    {
2416
                        var left = (BoundCall)assignmentTarget;
2417 2418 2419 2420 2421 2422 2423 2424

                        Debug.Assert(left.Method.RefKind != RefKind.None);
                        EmitCallExpression(left, UseKind.UsedAsAddress);

                        lhsUsesStack = true;
                    }
                    break;

P
Pilchie 已提交
2425 2426 2427 2428 2429
                case BoundKind.PropertyAccess:
                case BoundKind.IndexerAccess:
                // Property access should have been rewritten.
                case BoundKind.PreviousSubmissionReference:
                    // Script references are lowered to a this reference and a field access.
2430 2431 2432 2433 2434 2435
                    throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);

                case BoundKind.PseudoVariable:
                    EmitPseudoVariableAddress((BoundPseudoVariable)assignmentTarget);
                    lhsUsesStack = true;
                    break;
2436 2437 2438 2439 2440

                case BoundKind.ModuleVersionId:
                case BoundKind.InstrumentationPayloadRoot:
                    break;

2441 2442
                case BoundKind.AssignmentOperator:
                    var assignment = (BoundAssignmentOperator)assignmentTarget;
2443
                    if (!assignment.IsRef)
2444 2445 2446 2447 2448 2449
                    {
                        goto default;
                    }
                    EmitAssignmentExpression(assignment, UseKind.UsedAsAddress);
                    break;

2450 2451
                default:
                    throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);
P
Pilchie 已提交
2452
            }
2453

P
Pilchie 已提交
2454 2455 2456 2457 2458
            return lhsUsesStack;
        }

        private void EmitAssignmentValue(BoundAssignmentOperator assignmentOperator)
        {
2459
            if (!assignmentOperator.IsRef)
P
Pilchie 已提交
2460 2461 2462 2463 2464
            {
                EmitExpression(assignmentOperator.Right, used: true);
            }
            else
            {
V
vsadov 已提交
2465
                int exprTempsBefore = _expressionTemps?.Count ?? 0;
2466
                BoundExpression lhs = assignmentOperator.Left;
2467

2468 2469
                // NOTE: passing "ReadOnlyStrict" here. 
                //       we should not get an address of a copy if at all possible
2470
                LocalDefinition temp = EmitAddress(assignmentOperator.Right, lhs.GetRefKind() == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
2471 2472 2473 2474 2475

                // Generally taking a ref for the purpose of ref assignment should not be done on homeless values
                // however, there are very rare cases when we need to get a ref off a temp in synthetic code.
                // Retain those temps for the extent of the encompassing expression.
                AddExpressionTemp(temp);
V
vsadov 已提交
2476

2477 2478
                var exprTempsAfter = _expressionTemps?.Count ?? 0;

V
vsadov 已提交
2479
                // are we, by the way, ref-assigning to something that lives longer than encompassing expression?
2480
                Debug.Assert(lhs.Kind != BoundKind.Parameter || exprTempsAfter <= exprTempsBefore);
2481

2482 2483
                if (lhs.Kind == BoundKind.Local && ((BoundLocal)lhs).LocalSymbol.SynthesizedKind.IsLongLived())
                {
V
vsadov 已提交
2484 2485
                    // This situation is extremely rare. We are assigning a ref to a local with unknown lifetime
                    // while computing that ref required expression temps.
2486
                    //
V
vsadov 已提交
2487 2488
                    // We cannot reuse any of those temps and must leak them from the retained set.
                    // Any of them could be directly or indirectly referred by the LHS after the assignment.
2489
                    // and we do not know the scope of the LHS - could be the whole method.
V
vsadov 已提交
2490
                    if (exprTempsAfter > exprTempsBefore)
2491 2492 2493 2494
                    {
                        _expressionTemps.Count = exprTempsBefore;
                    }
                }
P
Pilchie 已提交
2495 2496 2497
            }
        }

2498
        private LocalDefinition EmitAssignmentDuplication(BoundAssignmentOperator assignmentOperator, UseKind useKind, bool lhsUsesStack)
P
Pilchie 已提交
2499 2500
        {
            LocalDefinition temp = null;
2501
            if (useKind != UseKind.Unused)
P
Pilchie 已提交
2502
            {
2503
                _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
2504 2505 2506 2507 2508 2509 2510 2511 2512

                if (lhsUsesStack)
                {
                    // Today we sometimes have a case where we assign a ref directly to a temporary of ref type:
                    //
                    // ref int addr = ref N().y;  <-- copies the address by value; no indirection
                    // int sum = addr + 10;
                    // addr = sum;
                    //
2513
                    // If we have something like:
P
Pilchie 已提交
2514 2515 2516 2517 2518 2519 2520
                    //
                    // ref int t1 = (ref int t2 = ref M().s); 
                    //
                    // or the even more odd:
                    //
                    // int t1 = (ref int t2 = ref M().s);
                    //
2521 2522 2523 2524 2525 2526 2527 2528
                    // We need to figure out which of the situations above we are in, and ensure that the
                    // correct kind of temporary is created here. And also that either its value or its
                    // indirected value is read out after the store, in EmitAssignmentPostfix, below.

                    temp = AllocateTemp(
                        assignmentOperator.Left.Type,
                        assignmentOperator.Left.Syntax,
                        assignmentOperator.IsRef ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
2529
                    _builder.EmitLocalStore(temp);
P
Pilchie 已提交
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
                }
            }
            return temp;
        }

        private void EmitStore(BoundAssignmentOperator assignment)
        {
            BoundExpression expression = assignment.Left;
            switch (expression.Kind)
            {
                case BoundKind.FieldAccess:
                    EmitFieldStore((BoundFieldAccess)expression);
                    break;

                case BoundKind.Local:
                    // If we are doing a 'normal' local assignment like 'int t = 10;', or
                    // if we are initializing a temporary like 'ref int t = ref M().s;' then
                    // we just emit a local store. If we are doing an assignment through
                    // a ref local temporary then we assume that the instruction to load
                    // the address is already on the stack, and we must indirect through it.

                    // See the comments in EmitAssignmentExpression above for details.
                    BoundLocal local = (BoundLocal)expression;
2553
                    if (local.LocalSymbol.RefKind != RefKind.None && !assignment.IsRef)
P
Pilchie 已提交
2554
                    {
2555
                        EmitIndirectStore(local.LocalSymbol.Type, local.Syntax);
P
Pilchie 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
                    }
                    else
                    {
                        if (IsStackLocal(local.LocalSymbol))
                        {
                            // assign to stack var == leave original value on stack
                            break;
                        }
                        else
                        {
2566
                            _builder.EmitLocalStore(GetLocal(local));
P
Pilchie 已提交
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
                        }
                    }
                    break;

                case BoundKind.ArrayAccess:
                    var array = ((BoundArrayAccess)expression).Expression;
                    var arrayType = (ArrayTypeSymbol)array.Type;
                    EmitArrayElementStore(arrayType, expression.Syntax);
                    break;

                case BoundKind.ThisReference:
                    EmitThisStore((BoundThisReference)expression);
                    break;

                case BoundKind.Parameter:
2582
                    EmitParameterStore((BoundParameter)expression, assignment.IsRef);
P
Pilchie 已提交
2583 2584 2585 2586 2587 2588 2589
                    break;

                case BoundKind.Dup:
                    Debug.Assert(((BoundDup)expression).RefKind != RefKind.None);
                    EmitIndirectStore(expression.Type, expression.Syntax);
                    break;

2590
                case BoundKind.ConditionalOperator:
2591
                    Debug.Assert(((BoundConditionalOperator)expression).IsRef);
2592
                    EmitIndirectStore(expression.Type, expression.Syntax);
P
Pilchie 已提交
2593 2594 2595 2596
                    break;

                case BoundKind.RefValueOperator:
                case BoundKind.PointerIndirectionOperator:
2597
                case BoundKind.PseudoVariable:
P
Pilchie 已提交
2598 2599 2600
                    EmitIndirectStore(expression.Type, expression.Syntax);
                    break;

2601 2602 2603
                case BoundKind.Sequence:
                    {
                        var sequence = (BoundSequence)expression;
2604
                        EmitStore(assignment.Update(sequence.Value, assignment.Right, assignment.IsRef, assignment.Type));
2605 2606 2607
                    }
                    break;

2608 2609 2610 2611 2612
                case BoundKind.Call:
                    Debug.Assert(((BoundCall)expression).Method.RefKind != RefKind.None);
                    EmitIndirectStore(expression.Type, expression.Syntax);
                    break;

2613
                case BoundKind.ModuleVersionId:
J
John Hamby 已提交
2614
                    EmitModuleVersionIdStore((BoundModuleVersionId)expression);
2615 2616
                    break;

J
John Hamby 已提交
2617 2618
                case BoundKind.InstrumentationPayloadRoot:
                    EmitInstrumentationPayloadRootStore((BoundInstrumentationPayloadRoot)expression);
2619 2620
                    break;

2621 2622
                case BoundKind.AssignmentOperator:
                    var nested = (BoundAssignmentOperator)expression;
2623
                    if (!nested.IsRef)
2624 2625 2626 2627 2628 2629
                    {
                        goto default;
                    }
                    EmitIndirectStore(nested.Type, expression.Syntax);
                    break;

P
Pilchie 已提交
2630 2631 2632 2633 2634 2635 2636
                case BoundKind.PreviousSubmissionReference:
                // Script references are lowered to a this reference and a field access.
                default:
                    throw ExceptionUtilities.UnexpectedValue(expression.Kind);
            }
        }

2637
        private void EmitAssignmentPostfix(BoundAssignmentOperator assignment, LocalDefinition temp, UseKind useKind)
P
Pilchie 已提交
2638 2639 2640
        {
            if (temp != null)
            {
2641 2642 2643 2644 2645 2646 2647 2648
                if (useKind == UseKind.UsedAsAddress)
                {
                    _builder.EmitLocalAddress(temp);
                }
                else
                {
                    _builder.EmitLocalLoad(temp);
                }
P
Pilchie 已提交
2649 2650
                FreeTemp(temp);
            }
2651

2652
            if (useKind == UseKind.UsedAsValue && assignment.IsRef)
2653 2654 2655
            {
                EmitLoadIndirect(assignment.Type, assignment.Syntax);
            }
P
Pilchie 已提交
2656 2657 2658 2659 2660 2661
        }

        private void EmitThisStore(BoundThisReference thisRef)
        {
            Debug.Assert(thisRef.Type.IsValueType);

2662
            _builder.EmitOpCode(ILOpCode.Stobj);
P
Pilchie 已提交
2663 2664 2665
            EmitSymbolToken(thisRef.Type, thisRef.Syntax);
        }

2666
        private void EmitArrayElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
P
Pilchie 已提交
2667
        {
2668
            if (arrayType.IsSZArray)
P
Pilchie 已提交
2669 2670 2671 2672 2673
            {
                EmitVectorElementStore(arrayType, syntaxNode);
            }
            else
            {
2674
                _builder.EmitArrayElementStore(Emit.PEModuleBuilder.Translate(arrayType), syntaxNode, _diagnostics);
P
Pilchie 已提交
2675 2676 2677 2678 2679 2680
            }
        }

        /// <summary>
        /// Emit an element store instruction for a single dimensional array.
        /// </summary>
2681
        private void EmitVectorElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
P
Pilchie 已提交
2682
        {
2683
            var elementType = arrayType.ElementType;
P
Pilchie 已提交
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695

            if (elementType.IsEnumType())
            {
                //underlying primitives do not need type tokens.
                elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
            }

            switch (elementType.PrimitiveTypeCode)
            {
                case Microsoft.Cci.PrimitiveTypeCode.Boolean:
                case Microsoft.Cci.PrimitiveTypeCode.Int8:
                case Microsoft.Cci.PrimitiveTypeCode.UInt8:
2696
                    _builder.EmitOpCode(ILOpCode.Stelem_i1);
P
Pilchie 已提交
2697 2698 2699 2700 2701
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Char:
                case Microsoft.Cci.PrimitiveTypeCode.Int16:
                case Microsoft.Cci.PrimitiveTypeCode.UInt16:
2702
                    _builder.EmitOpCode(ILOpCode.Stelem_i2);
P
Pilchie 已提交
2703 2704 2705 2706
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int32:
                case Microsoft.Cci.PrimitiveTypeCode.UInt32:
2707
                    _builder.EmitOpCode(ILOpCode.Stelem_i4);
P
Pilchie 已提交
2708 2709 2710 2711
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int64:
                case Microsoft.Cci.PrimitiveTypeCode.UInt64:
2712
                    _builder.EmitOpCode(ILOpCode.Stelem_i8);
P
Pilchie 已提交
2713 2714 2715 2716 2717
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.Pointer:
2718
                    _builder.EmitOpCode(ILOpCode.Stelem_i);
P
Pilchie 已提交
2719 2720 2721
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float32:
2722
                    _builder.EmitOpCode(ILOpCode.Stelem_r4);
P
Pilchie 已提交
2723 2724 2725
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float64:
2726
                    _builder.EmitOpCode(ILOpCode.Stelem_r8);
P
Pilchie 已提交
2727 2728 2729 2730 2731
                    break;

                default:
                    if (elementType.IsVerifierReference())
                    {
2732
                        _builder.EmitOpCode(ILOpCode.Stelem_ref);
P
Pilchie 已提交
2733 2734 2735
                    }
                    else
                    {
2736
                        _builder.EmitOpCode(ILOpCode.Stelem);
P
Pilchie 已提交
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
                        EmitSymbolToken(elementType, syntaxNode);
                    }
                    break;
            }
        }

        private void EmitFieldStore(BoundFieldAccess fieldAccess)
        {
            var field = fieldAccess.FieldSymbol;

            if (field.IsVolatile)
            {
2749
                _builder.EmitOpCode(ILOpCode.Volatile);
P
Pilchie 已提交
2750 2751
            }

2752
            _builder.EmitOpCode(field.IsStatic ? ILOpCode.Stsfld : ILOpCode.Stfld);
P
Pilchie 已提交
2753 2754 2755
            EmitSymbolToken(field, fieldAccess.Syntax);
        }

2756
        private void EmitParameterStore(BoundParameter parameter, bool refAssign)
P
Pilchie 已提交
2757 2758 2759
        {
            int slot = ParameterSlot(parameter);

2760
            if (parameter.ParameterSymbol.RefKind != RefKind.None && !refAssign)
P
Pilchie 已提交
2761 2762 2763
            {
                //NOTE: we should have the actual parameter already loaded, 
                //now need to do a store to where it points to
2764
                EmitIndirectStore(parameter.ParameterSymbol.Type, parameter.Syntax);
P
Pilchie 已提交
2765
            }
2766 2767 2768 2769
            else
            {
                _builder.EmitStoreArgumentOpcode(slot);
            }
P
Pilchie 已提交
2770 2771
        }

2772
        private void EmitIndirectStore(TypeSymbol type, SyntaxNode syntaxNode)
P
Pilchie 已提交
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
        {
            if (type.IsEnumType())
            {
                //underlying primitives do not need type tokens.
                type = ((NamedTypeSymbol)type).EnumUnderlyingType;
            }

            switch (type.PrimitiveTypeCode)
            {
                case Microsoft.Cci.PrimitiveTypeCode.Boolean:
                case Microsoft.Cci.PrimitiveTypeCode.Int8:
                case Microsoft.Cci.PrimitiveTypeCode.UInt8:
2785
                    _builder.EmitOpCode(ILOpCode.Stind_i1);
P
Pilchie 已提交
2786 2787 2788 2789 2790
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Char:
                case Microsoft.Cci.PrimitiveTypeCode.Int16:
                case Microsoft.Cci.PrimitiveTypeCode.UInt16:
2791
                    _builder.EmitOpCode(ILOpCode.Stind_i2);
P
Pilchie 已提交
2792 2793 2794 2795
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int32:
                case Microsoft.Cci.PrimitiveTypeCode.UInt32:
2796
                    _builder.EmitOpCode(ILOpCode.Stind_i4);
P
Pilchie 已提交
2797 2798 2799 2800
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int64:
                case Microsoft.Cci.PrimitiveTypeCode.UInt64:
2801
                    _builder.EmitOpCode(ILOpCode.Stind_i8);
P
Pilchie 已提交
2802 2803 2804 2805 2806
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.Pointer:
2807
                    _builder.EmitOpCode(ILOpCode.Stind_i);
P
Pilchie 已提交
2808 2809 2810
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float32:
2811
                    _builder.EmitOpCode(ILOpCode.Stind_r4);
P
Pilchie 已提交
2812 2813 2814
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float64:
2815
                    _builder.EmitOpCode(ILOpCode.Stind_r8);
P
Pilchie 已提交
2816 2817 2818 2819 2820
                    break;

                default:
                    if (type.IsVerifierReference())
                    {
2821
                        _builder.EmitOpCode(ILOpCode.Stind_ref);
P
Pilchie 已提交
2822 2823 2824
                    }
                    else
                    {
2825
                        _builder.EmitOpCode(ILOpCode.Stobj);
P
Pilchie 已提交
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
                        EmitSymbolToken(type, syntaxNode);
                    }
                    break;
            }
        }

        private void EmitPopIfUnused(bool used)
        {
            if (!used)
            {
2836
                _builder.EmitOpCode(ILOpCode.Pop);
P
Pilchie 已提交
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
            }
        }

        private void EmitIsExpression(BoundIsOperator isOp, bool used)
        {
            var operand = isOp.Operand;
            EmitExpression(operand, used);
            if (used)
            {
                Debug.Assert((object)operand.Type != null);
                if (!operand.Type.IsVerifierReference())
                {
2849
                    // box the operand for isinst if it is not a verifier reference
P
Pilchie 已提交
2850 2851
                    EmitBox(operand.Type, operand.Syntax);
                }
2852
                _builder.EmitOpCode(ILOpCode.Isinst);
P
Pilchie 已提交
2853
                EmitSymbolToken(isOp.TargetType.Type, isOp.Syntax);
2854 2855
                _builder.EmitOpCode(ILOpCode.Ldnull);
                _builder.EmitOpCode(ILOpCode.Cgt_un);
P
Pilchie 已提交
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
            }
        }

        private void EmitAsExpression(BoundAsOperator asOp, bool used)
        {
            Debug.Assert(!asOp.Conversion.Kind.IsImplicitConversion());

            var operand = asOp.Operand;
            EmitExpression(operand, used);

            if (used)
            {
                var operandType = operand.Type;
                var targetType = asOp.Type;
                Debug.Assert((object)targetType != null);
                if ((object)operandType != null && !operandType.IsVerifierReference())
                {
2873
                    // box the operand for isinst if it is not a verifier reference
P
Pilchie 已提交
2874 2875
                    EmitBox(operandType, operand.Syntax);
                }
2876
                _builder.EmitOpCode(ILOpCode.Isinst);
P
Pilchie 已提交
2877 2878 2879 2880
                EmitSymbolToken(targetType, asOp.Syntax);
                if (!targetType.IsVerifierReference())
                {
                    // We need to unbox if the target type is not a reference type
2881
                    _builder.EmitOpCode(ILOpCode.Unbox_any);
P
Pilchie 已提交
2882 2883 2884 2885 2886
                    EmitSymbolToken(targetType, asOp.Syntax);
                }
            }
        }

2887
        private void EmitDefaultValue(TypeSymbol type, bool used, SyntaxNode syntaxNode)
2888
        {
2889
            if (used)
2890
            {
2891
                // default type parameter values must be emitted as 'initobj' regardless of constraints
2892
                if (!type.IsTypeParameter() && type.SpecialType != SpecialType.System_Decimal)
2893
                {
2894 2895 2896 2897 2898 2899
                    var constantValue = type.GetDefaultValue();
                    if (constantValue != null)
                    {
                        _builder.EmitConstantValue(constantValue);
                        return;
                    }
2900
                }
2901

V
vsadov 已提交
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
                if (type.IsPointerType() || type.SpecialType == SpecialType.System_UIntPtr)
                {
                    // default(whatever*) and default(UIntPtr) can be emitted as:
                    _builder.EmitOpCode(ILOpCode.Ldc_i4_0);
                    _builder.EmitOpCode(ILOpCode.Conv_u);
                }
                else if (type.SpecialType == SpecialType.System_IntPtr)
                {
                    _builder.EmitOpCode(ILOpCode.Ldc_i4_0);
                    _builder.EmitOpCode(ILOpCode.Conv_i);
                }
                else
V
vsadov 已提交
2914
                {
V
vsadov 已提交
2915 2916
                    EmitInitObj(type, true, syntaxNode);
                }
2917 2918 2919
            }
        }

2920
        private void EmitDefaultExpression(BoundDefaultExpression expression, bool used)
P
Pilchie 已提交
2921 2922 2923 2924 2925 2926 2927
        {
            Debug.Assert(expression.Type.SpecialType == SpecialType.System_Decimal ||
                expression.Type.GetDefaultValue() == null, "constant should be set on this expression");

            // Default value for the given default expression is not a constant
            // Expression must be of type parameter type or a non-primitive value type
            // Emit an initobj instruction for these cases
V
vsadov 已提交
2928
            EmitDefaultValue(expression.Type, used, expression.Syntax);
P
Pilchie 已提交
2929 2930
        }

2931
        private void EmitConstantExpression(TypeSymbol type, ConstantValue constantValue, bool used, SyntaxNode syntaxNode)
P
Pilchie 已提交
2932
        {
2933
            if (used)  // unused constant has no side-effects
P
Pilchie 已提交
2934 2935 2936 2937 2938 2939 2940 2941
            {
                // Null type parameter values must be emitted as 'initobj' rather than 'ldnull'.
                if (((object)type != null) && (type.TypeKind == TypeKind.TypeParameter) && constantValue.IsNull)
                {
                    EmitInitObj(type, used, syntaxNode);
                }
                else
                {
2942
                    _builder.EmitConstantValue(constantValue);
P
Pilchie 已提交
2943 2944 2945 2946
                }
            }
        }

2947
        private void EmitInitObj(TypeSymbol type, bool used, SyntaxNode syntaxNode)
P
Pilchie 已提交
2948 2949 2950
        {
            if (used)
            {
V
vsadov 已提交
2951 2952
                var temp = this.AllocateTemp(type, syntaxNode);
                _builder.EmitLocalAddress(temp);                  //  ldloca temp
V
vsadov 已提交
2953
                _builder.EmitOpCode(ILOpCode.Initobj);            //  initobj  <MyStruct>
V
vsadov 已提交
2954 2955 2956
                EmitSymbolToken(type, syntaxNode);
                _builder.EmitLocalLoad(temp);                     //  ldloc temp
                FreeTemp(temp);
P
Pilchie 已提交
2957 2958 2959
            }
        }

2960
        private void EmitGetTypeFromHandle(BoundTypeOf boundTypeOf)
2961 2962 2963 2964 2965 2966 2967
        {
            _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
            var getTypeMethod = boundTypeOf.GetTypeFromHandle;
            Debug.Assert((object)getTypeMethod != null); // Should have been checked during binding
            EmitSymbolToken(getTypeMethod, boundTypeOf.Syntax, null);
        }

P
Pilchie 已提交
2968 2969 2970
        private void EmitTypeOfExpression(BoundTypeOfOperator boundTypeOfOperator)
        {
            TypeSymbol type = boundTypeOfOperator.SourceType.Type;
2971
            _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
2972
            EmitSymbolToken(type, boundTypeOfOperator.SourceType.Syntax);
2973
            EmitGetTypeFromHandle(boundTypeOfOperator);
P
Pilchie 已提交
2974 2975 2976 2977 2978
        }

        private void EmitSizeOfExpression(BoundSizeOfOperator boundSizeOfOperator)
        {
            TypeSymbol type = boundSizeOfOperator.SourceType.Type;
2979
            _builder.EmitOpCode(ILOpCode.Sizeof);
P
Pilchie 已提交
2980 2981 2982
            EmitSymbolToken(type, boundSizeOfOperator.SourceType.Syntax);
        }

J
John Hamby 已提交
2983
        private void EmitMethodDefIndexExpression(BoundMethodDefIndex node)
J
More  
John Hamby 已提交
2984
        {
J
John Hamby 已提交
2985 2986
            Debug.Assert(node.Method.IsDefinition);
            Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
J
John Hamby 已提交
2987
            _builder.EmitOpCode(ILOpCode.Ldtoken);
S
Shyam N 已提交
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998

            // For partial methods, we emit pseudo token based on the symbol for the partial
            // definition part as opposed to the symbol for the partial implementation part.
            // We will need to resolve the symbol associated with each pseudo token in order
            // to compute the real method definition tokens later. For partial methods, this
            // resolution can only succeed if the associated symbol is the symbol for the
            // partial definition and not the symbol for the partial implementation (see
            // MethodSymbol.ResolvedMethodImpl()).
            var symbol = node.Method.PartialDefinitionPart ?? node.Method;

            EmitSymbolToken(symbol, node.Syntax, null, encodeAsRawDefinitionToken: true);
2999 3000
        }

J
John Hamby 已提交
3001
        private void EmitMaximumMethodDefIndexExpression(BoundMaximumMethodDefIndex node)
J
John Hamby 已提交
3002 3003 3004 3005 3006 3007
        {
            Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
            _builder.EmitOpCode(ILOpCode.Ldtoken);
            _builder.EmitGreatestMethodToken();
        }

J
John Hamby 已提交
3008
        private void EmitModuleVersionIdLoad(BoundModuleVersionId node)
3009 3010
        {
            _builder.EmitOpCode(ILOpCode.Ldsfld);
J
John Hamby 已提交
3011
            EmitModuleVersionIdToken(node);
3012 3013
        }

J
John Hamby 已提交
3014
        private void EmitModuleVersionIdStore(BoundModuleVersionId node)
3015 3016
        {
            _builder.EmitOpCode(ILOpCode.Stsfld);
J
John Hamby 已提交
3017 3018 3019 3020 3021
            EmitModuleVersionIdToken(node);
        }

        private void EmitModuleVersionIdToken(BoundModuleVersionId node)
        {
J
John Hamby 已提交
3022
            _builder.EmitToken(_module.GetModuleVersionId(_module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
J
John Hamby 已提交
3023
        }
J
More.  
John Hamby 已提交
3024 3025 3026 3027 3028 3029 3030

        private void EmitModuleVersionIdStringLoad(BoundModuleVersionIdString node)
        {
            _builder.EmitOpCode(ILOpCode.Ldstr);
            _builder.EmitModuleVersionIdStringToken();
        }

J
John Hamby 已提交
3031
        private void EmitInstrumentationPayloadRootLoad(BoundInstrumentationPayloadRoot node)
J
John Hamby 已提交
3032 3033
        {
            _builder.EmitOpCode(ILOpCode.Ldsfld);
J
John Hamby 已提交
3034
            EmitInstrumentationPayloadRootToken(node);
J
John Hamby 已提交
3035 3036
        }

J
John Hamby 已提交
3037
        private void EmitInstrumentationPayloadRootStore(BoundInstrumentationPayloadRoot node)
J
John Hamby 已提交
3038 3039
        {
            _builder.EmitOpCode(ILOpCode.Stsfld);
3040
            EmitInstrumentationPayloadRootToken(node);
J
John Hamby 已提交
3041 3042 3043 3044
        }

        private void EmitInstrumentationPayloadRootToken(BoundInstrumentationPayloadRoot node)
        {
J
John Hamby 已提交
3045
            _builder.EmitToken(_module.GetInstrumentationPayloadRoot(node.AnalysisKind, _module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
3046 3047 3048 3049 3050 3051 3052
        }

        private void EmitSourceDocumentIndex(BoundSourceDocumentIndex node)
        {
            Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
            _builder.EmitOpCode(ILOpCode.Ldtoken);
            _builder.EmitSourceDocumentIndexToken(node.Document);
P
Pilchie 已提交
3053 3054 3055 3056
        }

        private void EmitMethodInfoExpression(BoundMethodInfo node)
        {
3057
            _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
3058 3059 3060 3061 3062 3063 3064
            EmitSymbolToken(node.Method, node.Syntax, null);

            MethodSymbol getMethod = node.GetMethodFromHandle;
            Debug.Assert((object)getMethod != null);

            if (getMethod.ParameterCount == 1)
            {
3065
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
P
Pilchie 已提交
3066 3067 3068 3069
            }
            else
            {
                Debug.Assert(getMethod.ParameterCount == 2);
3070
                _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
3071
                EmitSymbolToken(node.Method.ContainingType, node.Syntax);
3072
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
P
Pilchie 已提交
3073 3074 3075
            }

            EmitSymbolToken(getMethod, node.Syntax, null);
3076
            if (!TypeSymbol.Equals(node.Type, getMethod.ReturnType, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
3077
            {
3078
                _builder.EmitOpCode(ILOpCode.Castclass);
P
Pilchie 已提交
3079 3080 3081 3082 3083 3084
                EmitSymbolToken(node.Type, node.Syntax);
            }
        }

        private void EmitFieldInfoExpression(BoundFieldInfo node)
        {
3085
            _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
3086 3087 3088 3089 3090 3091
            EmitSymbolToken(node.Field, node.Syntax);
            MethodSymbol getField = node.GetFieldFromHandle;
            Debug.Assert((object)getField != null);

            if (getField.ParameterCount == 1)
            {
3092
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
P
Pilchie 已提交
3093 3094 3095 3096
            }
            else
            {
                Debug.Assert(getField.ParameterCount == 2);
3097
                _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
3098
                EmitSymbolToken(node.Field.ContainingType, node.Syntax);
3099
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
P
Pilchie 已提交
3100 3101 3102
            }

            EmitSymbolToken(getField, node.Syntax, null);
3103
            if (!TypeSymbol.Equals(node.Type, getField.ReturnType, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
3104
            {
3105
                _builder.EmitOpCode(ILOpCode.Castclass);
P
Pilchie 已提交
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
                EmitSymbolToken(node.Type, node.Syntax);
            }
        }

        /// <summary>
        /// Emit code for a conditional (aka ternary) operator.
        /// </summary>
        /// <remarks>
        /// (b ? x : y) becomes
        ///     push b
        ///     if pop then goto CONSEQUENCE
        ///     push y
        ///     goto DONE
        ///   CONSEQUENCE:
        ///     push x
        ///   DONE:
        /// </remarks>
        private void EmitConditionalOperator(BoundConditionalOperator expr, bool used)
        {
            Debug.Assert(expr.ConstantValue == null, "Constant value should have been emitted directly");

            object consequenceLabel = new object();
            object doneLabel = new object();

            EmitCondBranch(expr.Condition, ref consequenceLabel, sense: true);
            EmitExpression(expr.Alternative, used);

            //
            // III.1.8.1.3 Merging stack states
            // . . . 
            // Let T be the type from the slot on the newly computed state and S
            // be the type from the corresponding slot on the previously stored state. The merged type, U, shall
            // be computed as follows (recall that S := T is the compatibility function defined
            // in §III.1.8.1.2.2):
            // 1. if S := T then U=S
            // 2. Otherwise, if T := S then U=T
            // 3. Otherwise, if S and T are both object types, then let V be the closest common supertype of S and T then U=V.
            // 4. Otherwise, the merge shall fail.
            //
            // When the target merge type is an interface that one or more classes implement, we emit static casts
            // from any class to the target interface.
            // You may think that it's possible to elide one of the static casts and have the CLR recognize
            // that merging a class and interface should succeed if the class implements the interface. Unfortunately,
            // it seems that either PEVerify or the runtime/JIT verifier will complain at you if you try to remove
            // either of the casts.
            //
            var mergeTypeOfAlternative = StackMergeType(expr.Alternative);
            if (used)
            {
                if (IsVarianceCast(expr.Type, mergeTypeOfAlternative))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfAlternative = expr.Type;
                }
3160
                else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfAlternative, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
3161 3162 3163 3164 3165
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                }
            }

3166
            _builder.EmitBranch(ILOpCode.Br, doneLabel);
P
Pilchie 已提交
3167 3168
            if (used)
            {
C
Charles Stoner 已提交
3169
                // If we get to consequenceLabel, we should not have Alternative on stack, adjust for that.
3170
                _builder.AdjustStack(-1);
P
Pilchie 已提交
3171 3172
            }

3173
            _builder.MarkLabel(consequenceLabel);
P
Pilchie 已提交
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183
            EmitExpression(expr.Consequence, used);

            if (used)
            {
                var mergeTypeOfConsequence = StackMergeType(expr.Consequence);
                if (IsVarianceCast(expr.Type, mergeTypeOfConsequence))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfConsequence = expr.Type;
                }
3184
                else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfConsequence, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
3185 3186 3187 3188 3189
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                }
            }

3190
            _builder.MarkLabel(doneLabel);
P
Pilchie 已提交
3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
        }

        /// <summary>
        /// Emit code for a null-coalescing operator.
        /// </summary>
        /// <remarks>
        /// x ?? y becomes
        ///   push x
        ///   dup x
        ///   if pop != null goto LEFT_NOT_NULL
        ///     pop 
        ///     push y
        ///   LEFT_NOT_NULL:
        /// </remarks>
        private void EmitNullCoalescingOperator(BoundNullCoalescingOperator expr, bool used)
        {
3207
            Debug.Assert(expr.LeftConversion.IsIdentity, "coalesce with nontrivial left conversions are lowered into conditional.");
P
Pilchie 已提交
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
            Debug.Assert(expr.Type.IsReferenceType);

            EmitExpression(expr.LeftOperand, used: true);

            // See the notes about verification type merges in EmitConditionalOperator
            var mergeTypeOfLeftValue = StackMergeType(expr.LeftOperand);
            if (used)
            {
                if (IsVarianceCast(expr.Type, mergeTypeOfLeftValue))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfLeftValue = expr.Type;
                }
3221
                else if (expr.Type.IsInterfaceType() && !TypeSymbol.Equals(expr.Type, mergeTypeOfLeftValue, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
3222 3223 3224 3225
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                }

3226
                _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
3227 3228 3229 3230 3231 3232 3233 3234
            }

            if (expr.Type.IsTypeParameter())
            {
                EmitBox(expr.Type, expr.LeftOperand.Syntax);
            }

            object ifLeftNotNullLabel = new object();
3235
            _builder.EmitBranch(ILOpCode.Brtrue, ifLeftNotNullLabel);
P
Pilchie 已提交
3236 3237 3238

            if (used)
            {
3239
                _builder.EmitOpCode(ILOpCode.Pop);
P
Pilchie 已提交
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252
            }

            EmitExpression(expr.RightOperand, used);
            if (used)
            {
                var mergeTypeOfRightValue = StackMergeType(expr.RightOperand);
                if (IsVarianceCast(expr.Type, mergeTypeOfRightValue))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfRightValue = expr.Type;
                }
            }

3253
            _builder.MarkLabel(ifLeftNotNullLabel);
P
Pilchie 已提交
3254 3255 3256
        }

        // Implicit casts are not emitted. As a result verifier may operate on a different 
3257
        // types from the types of operands when performing stack merges in coalesce/conditional.
P
Pilchie 已提交
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
        // Such differences are in general irrelevant since merging rules work the same way
        // for base and derived types.
        //
        // Situation becomes more complicated with delegates, arrays and interfaces since they 
        // allow implicit casts from types that do not derive from them. In such cases
        // we may need to introduce static casts in the code to prod the verifier to the 
        // right direction
        //
        // This helper returns actual type of array|interface|delegate expression ignoring implicit 
        // casts. This would be the effective stack merge type in the verifier.
        // 
        // NOTE: In cases where stack merge type cannot be determined, we just return null.
        //       We still must assume that it can be an array, delegate or interface though.
        private TypeSymbol StackMergeType(BoundExpression expr)
        {
            // these cases are not interesting. Merge type is the same or derived. No difference.
V
vsadov 已提交
3274
            if (!(expr.Type.IsInterfaceType() || expr.Type.IsDelegateType()))
P
Pilchie 已提交
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
            {
                return expr.Type;
            }

            // Dig through casts. We only need to check for expressions that -
            // 1) implicit casts
            // 2) transparently return operands, so we need to dig deeper
            // 3) stack values
            switch (expr.Kind)
            {
                case BoundKind.Conversion:
                    var conversion = (BoundConversion)expr;
                    var conversionKind = conversion.ConversionKind;
3288
                    Debug.Assert(conversionKind != ConversionKind.NullLiteral && conversionKind != ConversionKind.DefaultLiteral);
3289

P
Pilchie 已提交
3290
                    if (conversionKind.IsImplicitConversion() &&
3291
                        conversionKind != ConversionKind.MethodGroup &&
3292 3293
                        conversionKind != ConversionKind.NullLiteral &&
                        conversionKind != ConversionKind.DefaultLiteral)
P
Pilchie 已提交
3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
                    {
                        return StackMergeType(conversion.Operand);
                    }
                    break;

                case BoundKind.AssignmentOperator:
                    var assignment = (BoundAssignmentOperator)expr;
                    return StackMergeType(assignment.Right);

                case BoundKind.Sequence:
                    var sequence = (BoundSequence)expr;
                    return StackMergeType(sequence.Value);

                case BoundKind.Local:
                    var local = (BoundLocal)expr;
                    if (this.IsStackLocal(local.LocalSymbol))
                    {
                        // stack value, we cannot be sure what it is
                        return null;
                    }
                    break;

                case BoundKind.Dup:
                    // stack value, we cannot be sure what it is
                    return null;
            }

            return expr.Type;
        }

        // Although III.1.8.1.3 seems to imply that verifier understands variance casts.
        // It appears that verifier/JIT gets easily confused. 
        // So to not rely on whether that should work or not we will flag potentially 
        // "complicated" casts and make them static casts to ensure we are all on 
3328
        // the same page with what type should be tracked.
P
Pilchie 已提交
3329 3330
        private static bool IsVarianceCast(TypeSymbol to, TypeSymbol from)
        {
3331
            if (TypeSymbol.Equals(to, from, TypeCompareKind.ConsiderEverything2))
P
Pilchie 已提交
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345
            {
                return false;
            }

            if ((object)from == null)
            {
                // from unknown type - this could be a variance conversion.
                return true;
            }

            // while technically variance casts, array conversions do not seem to be a problem
            // unless the element types are converted via variance.
            if (to.IsArray())
            {
3346
                return IsVarianceCast(((ArrayTypeSymbol)to).ElementType, ((ArrayTypeSymbol)from).ElementType);
P
Pilchie 已提交
3347 3348
            }

3349
            return (to.IsDelegateType() && !TypeSymbol.Equals(to, from, TypeCompareKind.ConsiderEverything2)) ||
3350
                   (to.IsInterfaceType() && from.IsInterfaceType() && !from.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey((NamedTypeSymbol)to));
P
Pilchie 已提交
3351 3352
        }

3353
        private void EmitStaticCast(TypeSymbol to, SyntaxNode syntax)
P
Pilchie 已提交
3354 3355 3356 3357
        {
            Debug.Assert(to.IsVerifierReference());

            // From ILGENREC::GenQMark
C
Charles Stoner 已提交
3358
            // See VSWhidbey Bugs #49619 and 108643. If the destination type is an interface we need
P
Pilchie 已提交
3359 3360 3361 3362 3363 3364 3365 3366 3367
            // to force a static cast to be generated for any cast result expressions. The static cast
            // should be done before the unifying jump so the code is verifiable and to allow the JIT to
            // optimize it away. NOTE: Since there is no staticcast instruction, we implement static cast
            // with a stloc / ldloc to a temporary.
            // Bug: VSWhidbey/49619
            // Bug: VSWhidbey/108643
            // Bug: Devdiv/42645

            var temp = AllocateTemp(to, syntax);
3368 3369
            _builder.EmitLocalStore(temp);
            _builder.EmitLocalLoad(temp);
P
Pilchie 已提交
3370 3371 3372
            FreeTemp(temp);
        }

3373
        private void EmitBox(TypeSymbol type, SyntaxNode syntaxNode)
P
Pilchie 已提交
3374
        {
3375 3376
            Debug.Assert(!type.IsRefLikeType);

3377
            _builder.EmitOpCode(ILOpCode.Box);
P
Pilchie 已提交
3378 3379 3380
            EmitSymbolToken(type, syntaxNode);
        }
    }
S
Sam Harwell 已提交
3381
}