EmitStatement.cs 64.5 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 4 5 6 7 8 9 10 11 12 13 14 15

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
16
    internal partial class CodeGenerator
P
Pilchie 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    {
        private void EmitStatement(BoundStatement statement)
        {
            switch (statement.Kind)
            {
                case BoundKind.Block:
                    EmitBlock((BoundBlock)statement);
                    break;

                case BoundKind.SequencePoint:
                    this.EmitSequencePointStatement((BoundSequencePoint)statement);
                    break;

                case BoundKind.SequencePointWithSpan:
                    this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement);
                    break;

                case BoundKind.ExpressionStatement:
                    EmitExpression(((BoundExpressionStatement)statement).Expression, false);
                    break;

                case BoundKind.StatementList:
                    EmitStatementList((BoundStatementList)statement);
                    break;

                case BoundKind.ReturnStatement:
                    EmitReturnStatement((BoundReturnStatement)statement);
                    break;

                case BoundKind.GotoStatement:
                    EmitGotoStatement((BoundGotoStatement)statement);
                    break;

                case BoundKind.LabelStatement:
                    EmitLabelStatement((BoundLabelStatement)statement);
                    break;

                case BoundKind.ConditionalGoto:
                    EmitConditionalGoto((BoundConditionalGoto)statement);
                    break;

                case BoundKind.ThrowStatement:
                    EmitThrowStatement((BoundThrowStatement)statement);
                    break;

                case BoundKind.TryStatement:
                    EmitTryStatement((BoundTryStatement)statement);
                    break;

                case BoundKind.SwitchStatement:
                    EmitSwitchStatement((BoundSwitchStatement)statement);
                    break;

70 71
                case BoundKind.StateMachineScope:
                    EmitStateMachineScope((BoundStateMachineScope)statement);
P
Pilchie 已提交
72 73 74 75 76 77 78 79 80 81 82 83
                    break;

                case BoundKind.NoOpStatement:
                    EmitNoOpStatement((BoundNoOpStatement)statement);
                    break;

                default:
                    // Code gen should not be invoked if there are errors.
                    throw ExceptionUtilities.UnexpectedValue(statement.Kind);
            }

#if DEBUG
84
            if (_stackLocals == null || _stackLocals.Count == 0)
P
Pilchie 已提交
85
            {
86
                _builder.AssertStackEmpty();
P
Pilchie 已提交
87 88 89 90
            }
#endif
        }

91 92
        private int EmitStatementAndCountInstructions(BoundStatement statement)
        {
93
            int n = _builder.InstructionsEmitted;
94
            this.EmitStatement(statement);
95
            return _builder.InstructionsEmitted - n;
96 97
        }

P
Pilchie 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110
        private void EmitStatementList(BoundStatementList list)
        {
            for (int i = 0, n = list.Statements.Length; i < n; i++)
            {
                EmitStatement(list.Statements[i]);
            }
        }

        private void EmitNoOpStatement(BoundNoOpStatement statement)
        {
            switch (statement.Flavor)
            {
                case NoOpStatementFlavor.Default:
V
vsadov 已提交
111
                    if (_ilEmitStyle == ILEmitStyle.Debug)
P
Pilchie 已提交
112
                    {
113
                        _builder.EmitOpCode(ILOpCode.Nop);
P
Pilchie 已提交
114 115 116 117
                    }
                    break;

                case NoOpStatementFlavor.AwaitYieldPoint:
118 119
                    Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null));
                    if (_asyncYieldPoints == null)
P
Pilchie 已提交
120
                    {
121 122
                        _asyncYieldPoints = ArrayBuilder<int>.GetInstance();
                        _asyncResumePoints = ArrayBuilder<int>.GetInstance();
P
Pilchie 已提交
123
                    }
124 125
                    Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
                    _asyncYieldPoints.Add(_builder.AllocateILMarker());
P
Pilchie 已提交
126 127 128
                    break;

                case NoOpStatementFlavor.AwaitResumePoint:
129 130 131 132
                    Debug.Assert(_asyncYieldPoints != null);
                    Debug.Assert(_asyncYieldPoints != null);
                    _asyncResumePoints.Add(_builder.AllocateILMarker());
                    Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count);
P
Pilchie 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(statement.Flavor);
            }
        }

        private void EmitThrowStatement(BoundThrowStatement node)
        {
            BoundExpression expr = node.ExpressionOpt;
            if (expr != null)
            {
                this.EmitExpression(expr, true);

                var exprType = expr.Type;
                // Expression type will be null for "throw null;".
149
                if (exprType?.TypeKind == TypeKind.TypeParameter)
P
Pilchie 已提交
150 151 152 153 154
                {
                    this.EmitBox(exprType, expr.Syntax);
                }
            }

155
            _builder.EmitThrow(isRethrow: expr == null);
P
Pilchie 已提交
156 157 158 159
        }

        private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto)
        {
160 161 162
            object label = boundConditionalGoto.Label;
            Debug.Assert(label != null);
            EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue);
P
Pilchie 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        }

        // 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed
        //pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at
        //the next instruction.

        private static bool CanPassToBrfalse(TypeSymbol ts)
        {
            if (ts.IsEnumType())
            {
                // valid enums are all primitives
                return true;
            }

            var tc = ts.PrimitiveTypeCode;
            switch (tc)
            {
                case Microsoft.Cci.PrimitiveTypeCode.Float32:
                case Microsoft.Cci.PrimitiveTypeCode.Float64:
                    return false;

                case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive:
                    // if this is a generic type param, verifier will want us to box
                    // EmitCondBranch knows that
                    return ts.IsReferenceType;

                default:
                    Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid);
                    Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void);

                    return true;
            }
        }

        private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense)
        {
            var opKind = condition.OperatorKind.Operator();

            Debug.Assert(opKind == BinaryOperatorKind.Equal ||
                        opKind == BinaryOperatorKind.NotEqual);

            BoundExpression nonConstOp;
            BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null;

            if (constOp != null)
            {
                nonConstOp = condition.Right;
            }
            else
            {
                constOp = (condition.Right.ConstantValue != null) ? condition.Right : null;
                if (constOp == null)
                {
                    return null;
                }
                nonConstOp = condition.Left;
            }

            var nonConstType = nonConstOp.Type;
            if (!CanPassToBrfalse(nonConstType))
            {
                return null;
            }

            bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean;
            bool isZero = constOp.ConstantValue.IsDefaultValue;

            // bool is special, only it can be compared to true and false...
            if (!isBool && !isZero)
            {
                return null;
            }

            // if comparing to zero, flip the sense
            if (isZero)
            {
                sense = !sense;
            }

            // if comparing != flip the sense
            if (opKind == BinaryOperatorKind.NotEqual)
            {
                sense = !sense;
            }

            return nonConstOp;
        }

251
        private const int IL_OP_CODE_ROW_LENGTH = 4;
P
Pilchie 已提交
252

253
        private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[]
P
Pilchie 已提交
254 255 256 257 258 259 260 261 262 263 264
        {
            //  <            <=               >                >=
            ILOpCode.Blt,    ILOpCode.Ble,    ILOpCode.Bgt,    ILOpCode.Bge,     // Signed
            ILOpCode.Bge,    ILOpCode.Bgt,    ILOpCode.Ble,    ILOpCode.Blt,     // Signed Invert
            ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un,  // Unsigned
            ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un,  // Unsigned Invert
            ILOpCode.Blt,    ILOpCode.Ble,    ILOpCode.Bgt,    ILOpCode.Bge,     // Float
            ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un,  // Float Invert
        };

        /// <summary>
C
Charles Stoner 已提交
265
        /// Produces opcode for a jump that corresponds to given operation and sense.
P
Pilchie 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        /// Also produces a reverse opcode - opcode for the same condition with inverted sense.
        /// </summary>
        private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode)
        {
            int opIdx;

            switch (op.OperatorKind.Operator())
            {
                case BinaryOperatorKind.Equal:
                    revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un;
                    return sense ? ILOpCode.Beq : ILOpCode.Bne_un;

                case BinaryOperatorKind.NotEqual:
                    revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq;
                    return sense ? ILOpCode.Bne_un : ILOpCode.Beq;

                case BinaryOperatorKind.LessThan:
                    opIdx = 0;
                    break;

                case BinaryOperatorKind.LessThanOrEqual:
                    opIdx = 1;
                    break;

                case BinaryOperatorKind.GreaterThan:
                    opIdx = 2;
                    break;

                case BinaryOperatorKind.GreaterThanOrEqual:
                    opIdx = 3;
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator());
            }

            if (IsUnsignedBinaryOperator(op))
            {
                opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned
            }
            else if (IsFloat(op.OperatorKind))
            {
                opIdx += 4 * IL_OP_CODE_ROW_LENGTH;  //float
            }

            int revOpIdx = opIdx;

            if (!sense)
            {
                opIdx += IL_OP_CODE_ROW_LENGTH; //invert op
            }
            else
            {
                revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev
            }

322 323
            revOpCode = s_condJumpOpCodes[revOpIdx];
            return s_condJumpOpCodes[opIdx];
P
Pilchie 已提交
324 325 326 327 328
        }

        // generate a jump to dest if (condition == sense) is true
        private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense)
        {
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
            _recursionDepth++;

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

                EmitCondBranchCore(condition, ref dest, sense);
            }
            else
            {
                EmitCondBranchCoreWithStackGuard(condition, ref dest, sense);
            }

            _recursionDepth--;
        }

        private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense)
        {
            Debug.Assert(_recursionDepth == 1);

            try
            {
                EmitCondBranchCore(condition, ref dest, sense);
                Debug.Assert(_recursionDepth == 1);
            }
            catch (Exception ex) when (StackGuard.IsInsufficientExecutionStackException(ex))
            {
                _diagnostics.Add(ErrorCode.ERR_InsufficientStack,
                                 BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition));
                throw new EmitCancelledException();
            }
        }

        private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense)
        {
C
CyrusNajmabadi 已提交
364
        oneMoreTime:
P
Pilchie 已提交
365 366 367 368 369 370 371 372 373 374

            ILOpCode ilcode;

            if (condition.ConstantValue != null)
            {
                bool taken = condition.ConstantValue.IsDefaultValue != sense;

                if (taken)
                {
                    dest = dest ?? new object();
375
                    _builder.EmitBranch(ILOpCode.Br, dest);
P
Pilchie 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
                }
                else
                {
                    // otherwise this branch will never be taken, so just fall through...
                }

                return;
            }

            switch (condition.Kind)
            {
                case BoundKind.BinaryOperator:
                    var binOp = (BoundBinaryOperator)condition;
                    bool testBothArgs = sense;

                    switch (binOp.OperatorKind.OperatorWithLogical())
                    {
                        case BinaryOperatorKind.LogicalOr:
                            testBothArgs = !testBothArgs;
                            // Fall through
                            goto case BinaryOperatorKind.LogicalAnd;

                        case BinaryOperatorKind.LogicalAnd:
                            if (testBothArgs)
                            {
                                // gotoif(a != sense) fallThrough
                                // gotoif(b == sense) dest
                                // fallThrough:

                                object fallThrough = null;

                                EmitCondBranch(binOp.Left, ref fallThrough, !sense);
                                EmitCondBranch(binOp.Right, ref dest, sense);

                                if (fallThrough != null)
                                {
412
                                    _builder.MarkLabel(fallThrough);
P
Pilchie 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
                                }
                            }
                            else
                            {
                                // gotoif(a == sense) labDest
                                // gotoif(b == sense) labDest

                                EmitCondBranch(binOp.Left, ref dest, sense);
                                condition = binOp.Right;
                                goto oneMoreTime;
                            }
                            return;

                        case BinaryOperatorKind.Equal:
                        case BinaryOperatorKind.NotEqual:
                            var reduced = TryReduce(binOp, ref sense);
                            if (reduced != null)
                            {
                                condition = reduced;
                                goto oneMoreTime;
                            }
                            // Fall through
                            goto case BinaryOperatorKind.LessThan;

                        case BinaryOperatorKind.LessThan:
                        case BinaryOperatorKind.LessThanOrEqual:
                        case BinaryOperatorKind.GreaterThan:
                        case BinaryOperatorKind.GreaterThanOrEqual:
                            EmitExpression(binOp.Left, true);
                            EmitExpression(binOp.Right, true);
                            ILOpCode revOpCode;
                            ilcode = CodeForJump(binOp, sense, out revOpCode);
                            dest = dest ?? new object();
446
                            _builder.EmitBranch(ilcode, dest, revOpCode);
P
Pilchie 已提交
447 448 449 450 451 452 453
                            return;
                    }

                    // none of above. 
                    // then it is regular binary expression - Or, And, Xor ...
                    goto default;

454
                case BoundKind.LoweredConditionalAccess:
455
                    {
456
                        var ca = (BoundLoweredConditionalAccess)condition;
457 458 459 460 461 462
                        var receiver = ca.Receiver;
                        var receiverType = receiver.Type;

                        // we need a copy if we deal with nonlocal value (to capture the value)
                        // or if we deal with stack local (reads are destructive)
                        var complexCase = !receiverType.IsReferenceType ||
463
                                          LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
464
                                          (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) ||
J
Jared Parsons 已提交
465
                                          (ca.WhenNullOpt?.IsDefaultValue() == false);
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481

                        if (complexCase)
                        {
                            goto default;
                        }

                        if (sense)
                        {
                            // gotoif(receiver != null) fallThrough
                            // gotoif(receiver.Access) dest
                            // fallThrough:

                            object fallThrough = null;

                            EmitCondBranch(receiver, ref fallThrough, sense: false);
                            EmitReceiverRef(receiver, isAccessConstrained: false);
482
                            EmitCondBranch(ca.WhenNotNull, ref dest, sense: true);
483 484 485

                            if (fallThrough != null)
                            {
486
                                _builder.MarkLabel(fallThrough);
487 488 489 490 491 492 493 494
                            }
                        }
                        else
                        {
                            // gotoif(receiver == null) labDest
                            // gotoif(!receiver.Access) labDest
                            EmitCondBranch(receiver, ref dest, sense: false);
                            EmitReceiverRef(receiver, isAccessConstrained: false);
495
                            condition = ca.WhenNotNull;
496 497 498 499 500
                            goto oneMoreTime;
                        }
                    }
                    return;

P
Pilchie 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
                case BoundKind.UnaryOperator:
                    var unOp = (BoundUnaryOperator)condition;
                    if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation)
                    {
                        sense = !sense;
                        condition = unOp.Operand;
                        goto oneMoreTime;
                    }
                    goto default;

                case BoundKind.IsOperator:
                    var isOp = (BoundIsOperator)condition;
                    var operand = isOp.Operand;
                    EmitExpression(operand, true);
                    Debug.Assert((object)operand.Type != null);
                    if (!operand.Type.IsVerifierReference())
                    {
518
                        // box the operand for isinst if it is not a verifier reference
P
Pilchie 已提交
519 520
                        EmitBox(operand.Type, operand.Syntax);
                    }
521
                    _builder.EmitOpCode(ILOpCode.Isinst);
P
Pilchie 已提交
522 523 524
                    EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax);
                    ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
                    dest = dest ?? new object();
525
                    _builder.EmitBranch(ilcode, dest);
P
Pilchie 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                    return;

                case BoundKind.Sequence:
                    var seq = (BoundSequence)condition;
                    EmitSequenceCondBranch(seq, ref dest, sense);
                    return;

                default:
                    EmitExpression(condition, true);

                    var conditionType = condition.Type;
                    if (conditionType.IsReferenceType && !conditionType.IsVerifierReference())
                    {
                        EmitBox(conditionType, condition.Syntax);
                    }

                    ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse;
                    dest = dest ?? new object();
544
                    _builder.EmitBranch(ilcode, dest);
P
Pilchie 已提交
545 546 547 548 549 550
                    return;
            }
        }

        private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense)
        {
551
            DefineLocals(sequence);
P
Pilchie 已提交
552 553
            EmitSideEffects(sequence);
            EmitCondBranch(sequence.Value, ref dest, sense);
554 555 556

            // sequence is used as a value, can release all locals
            FreeLocals(sequence, doNotRelease: null);
P
Pilchie 已提交
557 558 559 560
        }

        private void EmitLabelStatement(BoundLabelStatement boundLabelStatement)
        {
561
            _builder.MarkLabel(boundLabelStatement.Label);
P
Pilchie 已提交
562 563 564 565
        }

        private void EmitGotoStatement(BoundGotoStatement boundGotoStatement)
        {
566
            _builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label);
P
Pilchie 已提交
567 568
        }

569 570 571 572 573 574
        // used by HandleReturn method which tries to inject 
        // indirect ret sequence as a last statement in the block
        // that is the last statement of the current method
        // NOTE: it is important that there is no code after this "ret"
        //       it is desirable, for debug purposes, that this ret is emitted inside top level { } 
        private bool IsLastBlockInMethod(BoundBlock block)
P
Pilchie 已提交
575
        {
576
            if (_boundBody == block)
577 578 579 580 581 582
            {
                return true;
            }

            //sometimes top level node is a statement list containing 
            //epilogue and then a block. If we are having that block, it will do.
583
            var list = _boundBody as BoundStatementList;
584 585 586 587 588 589
            if (list != null && list.Statements.LastOrDefault() == block)
            {
                return true;
            }

            return false;
P
Pilchie 已提交
590 591 592 593
        }

        private void EmitBlock(BoundBlock block)
        {
594
            var hasLocals = !block.Locals.IsEmpty;
P
Pilchie 已提交
595 596 597

            if (hasLocals)
            {
598
                _builder.OpenLocalScope();
P
Pilchie 已提交
599

600
                foreach (var local in block.Locals)
P
Pilchie 已提交
601 602 603 604 605 606 607 608 609 610 611
                {
                    var declaringReferences = local.DeclaringSyntaxReferences;
                    DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax);
                }
            }

            foreach (var statement in block.Statements)
            {
                EmitStatement(statement);
            }

612
            if (_indirectReturnState == IndirectReturnState.Needed &&
613
                IsLastBlockInMethod(block))
P
Pilchie 已提交
614 615 616 617 618 619
            {
                HandleReturn();
            }

            if (hasLocals)
            {
620
                foreach (var local in block.Locals)
P
Pilchie 已提交
621 622 623 624
                {
                    FreeLocal(local);
                }

625
                _builder.CloseLocalScope();
P
Pilchie 已提交
626 627 628
            }
        }

629
        private void EmitStateMachineScope(BoundStateMachineScope scope)
P
Pilchie 已提交
630
        {
631
            _builder.OpenStateMachineScope();
P
Pilchie 已提交
632 633
            foreach (var field in scope.Fields)
            {
634
                _builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex);
P
Pilchie 已提交
635 636 637
            }

            EmitStatement(scope.Statement);
638
            _builder.CloseStateMachineScope();
P
Pilchie 已提交
639 640
        }

641
        // There are two ways a value can be returned from a function:
P
Pilchie 已提交
642 643
        // - Using ret opcode
        // - Store return value if any to a predefined temp and jump to the epilogue block
644 645
        // Sometimes ret is not an option (try/catch etc.). We also do this when emitting
        // debuggable code. This function is a stub for the logic that decides that.
P
Pilchie 已提交
646 647
        private bool ShouldUseIndirectReturn()
        {
648 649 650 651 652 653 654 655 656 657
            // If the method/lambda body is a block we define a sequence point for the closing brace of the body
            // and associate it with the ret instruction. If there is a return statement we need to store the value 
            // to a long-lived synthesized local since a sequence point requires an empty evaluation stack.
            //
            // The emitted pattern is:
            //   <evaluate return statement expression>
            //   stloc $ReturnValue
            //   ldloc  $ReturnValue // sequence point
            //   ret
            //
658
            // Do not emit this pattern if the method doesn't include user code or doesn't have a block body.
V
vsadov 已提交
659
            return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true ||
660
                   _builder.InExceptionHandler;
P
Pilchie 已提交
661 662
        }

663
        // Compiler generated return mapped to a block is very likely the synthetic return
P
Pilchie 已提交
664
        // that was added at the end of the last block of a void method by analysis.
665 666
        // This is likely to be the last return in the method, so if we have not yet
        // emitted return sequence, it is convenient to do it right here (if we can).
P
Pilchie 已提交
667 668 669
        private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement)
        {
            return boundReturnStatement.WasCompilerGenerated &&
670
                    (boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) &&
671
                    !_builder.InExceptionHandler;
P
Pilchie 已提交
672 673 674 675
        }

        private void EmitReturnStatement(BoundReturnStatement boundReturnStatement)
        {
676
            var expressionOpt = boundReturnStatement.ExpressionOpt;
677 678 679 680 681 682 683 684
            if (boundReturnStatement.RefKind == RefKind.None)
            {
                this.EmitExpression(expressionOpt, true);
            }
            else
            {
                this.EmitAddress(expressionOpt, AddressKind.Writeable);
            }
P
Pilchie 已提交
685 686 687

            if (ShouldUseIndirectReturn())
            {
688
                if (expressionOpt != null)
P
Pilchie 已提交
689
                {
690
                    _builder.EmitLocalStore(LazyReturnTemp);
P
Pilchie 已提交
691 692
                }

693
                if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement))
P
Pilchie 已提交
694 695 696 697 698
                {
                    HandleReturn();
                }
                else
                {
699
                    _builder.EmitBranch(ILOpCode.Br, s_returnLabel);
P
Pilchie 已提交
700

701
                    if (_indirectReturnState == IndirectReturnState.NotNeeded)
P
Pilchie 已提交
702
                    {
703
                        _indirectReturnState = IndirectReturnState.Needed;
P
Pilchie 已提交
704 705 706 707 708
                    }
                }
            }
            else
            {
709
                if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement))
P
Pilchie 已提交
710
                {
711
                    if (expressionOpt != null)
P
Pilchie 已提交
712
                    {
713
                        _builder.EmitLocalStore(LazyReturnTemp);
P
Pilchie 已提交
714 715 716 717 718 719
                    }

                    HandleReturn();
                }
                else
                {
720 721 722 723 724 725 726 727 728 729 730 731
                    if (expressionOpt != null)
                    {
                        // Ensure the return type has been translated. (Necessary
                        // for cases of untranslated anonymous types.)
                        var returnType = expressionOpt.Type;
                        var byRefType = returnType as ByRefReturnErrorTypeSymbol;
                        if ((object)byRefType != null)
                        {
                            returnType = byRefType.ReferencedType;
                        }
                        _module.Translate(returnType, boundReturnStatement.Syntax, _diagnostics);
                    }
732
                    _builder.EmitRet(expressionOpt == null);
P
Pilchie 已提交
733 734 735 736 737 738 739 740 741
                }
            }
        }

        private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false)
        {
            Debug.Assert(!statement.CatchBlocks.IsDefault);

            // Stack must be empty at beginning of try block.
742
            _builder.AssertStackEmpty();
P
Pilchie 已提交
743 744 745 746 747 748 749 750

            // IL requires catches and finally block to be distinct try
            // blocks so if the source contained both a catch and
            // a finally, nested scopes are emitted.
            bool emitNestedScopes = (!emitCatchesOnly &&
                (statement.CatchBlocks.Length > 0) &&
                (statement.FinallyBlockOpt != null));

751
            _builder.OpenLocalScope(ScopeType.TryCatchFinally);
P
Pilchie 已提交
752

753
            _builder.OpenLocalScope(ScopeType.Try);
P
Pilchie 已提交
754 755 756 757
            // IL requires catches and finally block to be distinct try
            // blocks so if the source contained both a catch and
            // a finally, nested scopes are emitted.

758
            _tryNestingLevel++;
P
Pilchie 已提交
759 760 761 762 763 764 765 766 767
            if (emitNestedScopes)
            {
                EmitTryStatement(statement, emitCatchesOnly: true);
            }
            else
            {
                EmitBlock(statement.TryBlock);
            }

768
            _tryNestingLevel--;
P
Pilchie 已提交
769
            // Close the Try scope
770
            _builder.CloseLocalScope();
P
Pilchie 已提交
771 772 773 774 775 776 777 778 779 780 781

            if (!emitNestedScopes)
            {
                foreach (var catchBlock in statement.CatchBlocks)
                {
                    EmitCatchBlock(catchBlock);
                }
            }

            if (!emitCatchesOnly && (statement.FinallyBlockOpt != null))
            {
782
                _builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally);
P
Pilchie 已提交
783 784 785
                EmitBlock(statement.FinallyBlockOpt);

                // close Finally scope
786
                _builder.CloseLocalScope();
P
Pilchie 已提交
787 788

                // close the whole try statement scope
789
                _builder.CloseLocalScope();
P
Pilchie 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

                // in a case where we emit surrogate Finally using Fault, we emit code like this
                //
                // try{
                //      . . .
                // } fault {
                //      finallyBlock;
                // }
                // finallyBlock;
                //
                // This is where the second copy of finallyBlock is emitted. 
                if (statement.PreferFaultHandler)
                {
                    var finallyClone = FinallyCloner.MakeFinallyClone(statement);
                    EmitBlock(finallyClone);
                }
            }
            else
            {
                // close the whole try statement scope
810
                _builder.CloseLocalScope();
P
Pilchie 已提交
811 812 813 814 815 816 817 818 819 820 821
            }
        }

        /// <remarks>
        /// The interesting part in the following method is the support for exception filters. 
        /// === Example:
        ///
        /// try
        /// {
        ///    TryBlock
        /// }
822
        /// catch (ExceptionType ex) when (Condition)
P
Pilchie 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
        /// {
        ///    Handler
        /// }
        ///
        /// gets emitted as something like ===>
        ///
        /// Try           
        ///     TryBlock
        /// Filter 
        ///     var tmp = Pop() as {ExceptionType}
        ///     if (tmp == null)
        ///     {
        ///         Push 0
        ///     }
        ///     else
        ///     {
        ///         ex = tmp
        ///         Push Condition ? 1 : 0
        ///     }
        /// End Filter // leaves 1 or 0 on the stack
        /// Catch      // gets called after finalization of nested exception frames if condition above produced 1
        ///     Pop    // CLR pushes the exception object again
        ///     variable ex can be used here
        ///     Handler
        /// EndCatch
        /// </remarks>
        private void EmitCatchBlock(BoundCatchBlock catchBlock)
        {
            object typeCheckFailedLabel = null;


854
            _builder.AdjustStack(1); // Account for exception on the stack.
P
Pilchie 已提交
855 856 857 858 859 860

            // Open appropriate exception handler scope. (Catch or Filter)
            // if it is a Filter, emit prologue that checks if the type on the stack
            // converts to what we want.
            if (catchBlock.ExceptionFilterOpt == null)
            {
861 862 863 864
                var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ?
                    _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) :
                    _module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics);

865
                _builder.OpenLocalScope(ScopeType.Catch, exceptionType);
P
Pilchie 已提交
866

867 868
                if (catchBlock.IsSynthesizedAsyncCatchAll)
                {
869 870
                    Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected
                    _asyncCatchHandlerOffset = _builder.AllocateILMarker();
871 872
                }

P
Pilchie 已提交
873 874 875 876 877 878
                // Dev12 inserts the sequence point on catch clause without a filter, just before 
                // the exception object is assigned to the variable.
                // 
                // Also in Dev12 the exception variable scope span starts right after the stloc instruction and 
                // ends right before leave instruction. So when stopped at the sequence point Dev12 inserts,
                // the exception variable is not visible. 
879
                if (_emitPdbSequencePoints)
P
Pilchie 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
                {
                    var syntax = catchBlock.Syntax as CatchClauseSyntax;
                    if (syntax != null)
                    {
                        TextSpan spSpan;
                        var declaration = syntax.Declaration;

                        if (declaration == null)
                        {
                            spSpan = syntax.CatchKeyword.Span;
                        }
                        else
                        {
                            spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End);
                        }

                        this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan);
                    }
                }
            }
            else
            {
902
                _builder.OpenLocalScope(ScopeType.Filter);
P
Pilchie 已提交
903 904 905 906 907 908

                // Filtering starts with simulating regular catch through a 
                // type check. If this is not our type then we are done.
                var typeCheckPassedLabel = new object();
                typeCheckFailedLabel = new object();

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
                if ((object)catchBlock.ExceptionTypeOpt != null)
                {
                    var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics);

                    _builder.EmitOpCode(ILOpCode.Isinst);
                    _builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics);
                    _builder.EmitOpCode(ILOpCode.Dup);
                    _builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel);
                    _builder.EmitOpCode(ILOpCode.Pop);
                    _builder.EmitIntConstant(0);
                    _builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel);
                }
                else
                {
                    // no formal exception type means we always pass the check
                }
P
Pilchie 已提交
925

926
                _builder.MarkLabel(typeCheckPassedLabel);
P
Pilchie 已提交
927 928
            }

929
            foreach (var local in catchBlock.Locals)
P
Pilchie 已提交
930
            {
931
                var declaringReferences = local.DeclaringSyntaxReferences;
P
Pilchie 已提交
932
                var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax;
933
                DefineLocal(local, localSyntax);
P
Pilchie 已提交
934 935 936 937 938 939 940
            }

            var exceptionSourceOpt = catchBlock.ExceptionSourceOpt;
            if (exceptionSourceOpt != null)
            {
                // here we have our exception on the stack in a form of a reference type (O)
                // it means that we have to "unbox" it before storing to the local 
C
Charles Stoner 已提交
941
                // if exception's type is a generic type parameter.
P
Pilchie 已提交
942 943 944
                if (!exceptionSourceOpt.Type.IsVerifierReference())
                {
                    Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters
945
                    _builder.EmitOpCode(ILOpCode.Unbox_any);
P
Pilchie 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
                    EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax);
                }

                BoundExpression exceptionSource = exceptionSourceOpt;
                while (exceptionSource.Kind == BoundKind.Sequence)
                {
                    var seq = (BoundSequence)exceptionSource;
                    EmitSideEffects(seq);
                    exceptionSource = seq.Value;
                }

                switch (exceptionSource.Kind)
                {
                    case BoundKind.Local:
                        var exceptionSourceLocal = (BoundLocal)exceptionSource;
                        Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None);
                        if (!IsStackLocal(exceptionSourceLocal.LocalSymbol))
                        {
964
                            _builder.EmitLocalStore(GetLocal(exceptionSourceLocal));
P
Pilchie 已提交
965 966 967 968 969 970 971 972 973
                        }

                        break;

                    case BoundKind.FieldAccess:
                        var left = (BoundFieldAccess)exceptionSource;
                        Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported");
                        Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter());

974 975 976 977 978 979
                        var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol;
                        if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0))
                        {
                            _builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex);
                        }

P
Pilchie 已提交
980 981 982
                        // When assigning to a field
                        // we need to push param address below the exception
                        var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax);
983
                        _builder.EmitLocalStore(temp);
P
Pilchie 已提交
984

985 986
                        var receiverTemp = EmitReceiverRef(left.ReceiverOpt);
                        Debug.Assert(receiverTemp == null);
P
Pilchie 已提交
987

988
                        _builder.EmitLocalLoad(temp);
989 990
                        FreeTemp(temp);

P
Pilchie 已提交
991 992 993 994 995 996 997 998 999
                        EmitFieldStore(left);
                        break;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind);
                }
            }
            else
            {
1000
                _builder.EmitOpCode(ILOpCode.Pop);
P
Pilchie 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009
            }

            // Emit the actual filter expression, if we have one, and normalize
            // results.
            if (catchBlock.ExceptionFilterOpt != null)
            {
                EmitCondExpr(catchBlock.ExceptionFilterOpt, true);
                // Normalize the return value because values other than 0 or 1
                // produce unspecified results.
1010 1011 1012
                _builder.EmitIntConstant(0);
                _builder.EmitOpCode(ILOpCode.Cgt_un);
                _builder.MarkLabel(typeCheckFailedLabel);
P
Pilchie 已提交
1013 1014

                // Now we are starting the actual handler
1015
                _builder.MarkFilterConditionEnd();
P
Pilchie 已提交
1016 1017 1018

                // Pop the exception; it should have already been stored to the
                // variable by the filter.
1019
                _builder.EmitOpCode(ILOpCode.Pop);
P
Pilchie 已提交
1020 1021 1022 1023
            }

            EmitBlock(catchBlock.Body);

1024
            _builder.CloseLocalScope();
P
Pilchie 已提交
1025 1026 1027 1028
        }

        private void EmitSwitchStatement(BoundSwitchStatement switchStatement)
        {
1029 1030 1031 1032 1033 1034
            var preambleOpt = switchStatement.LoweredPreambleOpt;
            if (preambleOpt != null)
            {
                EmitStatement(preambleOpt);
            }

P
Pilchie 已提交
1035
            // Switch expression must have a valid switch governing type
N
Neal Gafter 已提交
1036 1037
            Debug.Assert((object)switchStatement.Expression.Type != null);
            Debug.Assert(switchStatement.Expression.Type.IsValidSwitchGoverningType());
P
Pilchie 已提交
1038 1039

            // We must have rewritten nullable switch expression into non-nullable constructs.
N
Neal Gafter 已提交
1040
            Debug.Assert(!switchStatement.Expression.Type.IsNullableType());
P
Pilchie 已提交
1041

N
Neal Gafter 已提交
1042
            BoundExpression expression = switchStatement.Expression;
P
Pilchie 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
            ImmutableArray<BoundSwitchSection> switchSections = switchStatement.SwitchSections;
            GeneratedLabelSymbol breakLabel = switchStatement.BreakLabel;
            LabelSymbol constantTargetOpt = switchStatement.ConstantTargetOpt;

            if ((object)constantTargetOpt != null)
            {
                EmitConstantSwitchHeader(expression, constantTargetOpt);
            }
            else
            {
                // ConstantTargetOpt should be set to breakLabel for empty switch statement
                Debug.Assert(switchStatement.SwitchSections.Any());

                // Get switch case labels (indexed by their constant value) for emitting switch header and jump table
                LabelSymbol fallThroughLabel = breakLabel;
                KeyValuePair<ConstantValue, object>[] switchCaseLabels = GetSwitchCaseLabels(switchSections, ref fallThroughLabel);

                // CONSIDER: EmitSwitchHeader may modify the switchCaseLabels array by sorting it.
                // CONSIDER: Currently, only purpose of creating this switchCaseLabels array is for Emitting the switch header.
                // CONSIDER: If this requirement changes, we may want to pass in ArrayBuilder<KeyValuePair<ConstantValue, object>> instead.

                if (switchCaseLabels.Length == 0)
                {
                    // no case labels
                    EmitExpression(expression, used: false);
1068
                    _builder.EmitBranch(ILOpCode.Br, fallThroughLabel);
P
Pilchie 已提交
1069 1070 1071 1072 1073 1074 1075
                }
                else
                {
                    EmitSwitchHeader(switchStatement, expression, switchCaseLabels, fallThroughLabel);
                }
            }

1076
            EmitSwitchBody(switchStatement.InnerLocals, switchSections, breakLabel, switchStatement.Syntax);
P
Pilchie 已提交
1077 1078 1079 1080 1081 1082 1083
        }

        private static KeyValuePair<ConstantValue, object>[] GetSwitchCaseLabels(ImmutableArray<BoundSwitchSection> sections, ref LabelSymbol fallThroughLabel)
        {
            var labelsBuilder = ArrayBuilder<KeyValuePair<ConstantValue, object>>.GetInstance();
            foreach (var section in sections)
            {
N
Neal Gafter 已提交
1084
                foreach (BoundSwitchLabel boundLabel in section.SwitchLabels)
P
Pilchie 已提交
1085 1086
                {
                    var label = (SourceLabelSymbol)boundLabel.Label;
1087
                    if (label.IdentifierNodeOrToken.Kind() == SyntaxKind.DefaultSwitchLabel)
P
Pilchie 已提交
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
                    {
                        fallThroughLabel = label;
                    }
                    else
                    {
                        Debug.Assert(label.SwitchCaseLabelConstant != null
                            && SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(label.SwitchCaseLabelConstant));

                        labelsBuilder.Add(new KeyValuePair<ConstantValue, object>(label.SwitchCaseLabelConstant, label));
                    }
                }
            }

            return labelsBuilder.ToArrayAndFree();
        }

        private void EmitConstantSwitchHeader(BoundExpression expression, LabelSymbol target)
        {
            EmitExpression(expression, false);
1107
            _builder.EmitBranch(ILOpCode.Br, target);
P
Pilchie 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
        }

        private void EmitSwitchHeader(
            BoundSwitchStatement switchStatement,
            BoundExpression expression,
            KeyValuePair<ConstantValue, object>[] switchCaseLabels,
            LabelSymbol fallThroughLabel)
        {
            Debug.Assert(expression.ConstantValue == null);
            Debug.Assert((object)expression.Type != null &&
                expression.Type.IsValidSwitchGoverningType());
            Debug.Assert(switchCaseLabels.Length > 0);

            Debug.Assert(switchCaseLabels != null);

            LocalDefinition temp = null;
1124 1125
            LocalOrParameter key;
            BoundSequence sequence = null;
P
Pilchie 已提交
1126

1127
            if (expression.Kind == BoundKind.Sequence)
P
Pilchie 已提交
1128
            {
1129 1130 1131 1132 1133
                sequence = (BoundSequence)expression;
                DefineLocals(sequence);
                EmitSideEffects(sequence);
                expression = sequence.Value;
            }
P
Pilchie 已提交
1134

1135 1136 1137 1138 1139 1140 1141
            if (expression.Kind == BoundKind.SequencePointExpression)
            {
                var sequencePointExpression = (BoundSequencePointExpression)expression;
                EmitSequencePoint(sequencePointExpression);
                expression = sequencePointExpression.Expression;
            }

1142
            switch (expression.Kind)
1143
            {
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
                case BoundKind.Local:
                    var local = ((BoundLocal)expression).LocalSymbol;
                    if (local.RefKind == RefKind.None && !IsStackLocal(local))
                    {
                        key = this.GetLocal(local);
                        break;
                    }
                    goto default;

                case BoundKind.Parameter:
                    var parameter = (BoundParameter)expression;
                    if (parameter.ParameterSymbol.RefKind == RefKind.None)
                    {
                        key = ParameterSlot(parameter);
                        break;
                    }
                    goto default;

                default:
                    EmitExpression(expression, true);
                    temp = AllocateTemp(expression.Type, expression.Syntax);
1165
                    _builder.EmitLocalStore(temp);
1166 1167
                    key = temp;
                    break;
1168
            }
P
Pilchie 已提交
1169

1170 1171 1172
            // Emit switch jump table            
            if (expression.Type.SpecialType != SpecialType.System_String)
            {
1173
                _builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingType().PrimitiveTypeCode);
1174 1175 1176 1177
            }
            else
            {
                this.EmitStringSwitchJumpTable(switchStatement, switchCaseLabels, fallThroughLabel, key, expression.Syntax);
P
Pilchie 已提交
1178 1179 1180 1181 1182 1183
            }

            if (temp != null)
            {
                FreeTemp(temp);
            }
1184 1185 1186

            if (sequence != null)
            {
1187
                FreeLocals(sequence, doNotRelease: null);
1188
            }
P
Pilchie 已提交
1189 1190 1191 1192 1193 1194
        }

        private void EmitStringSwitchJumpTable(
            BoundSwitchStatement switchStatement,
            KeyValuePair<ConstantValue, object>[] switchCaseLabels,
            LabelSymbol fallThroughLabel,
1195
            LocalOrParameter key,
P
Pilchie 已提交
1196 1197 1198 1199
            CSharpSyntaxNode syntaxNode)
        {
            LocalDefinition keyHash = null;

1200
            // Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member).
1201
            if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length))
P
Pilchie 已提交
1202
            {
1203
                Debug.Assert(_module.SupportsPrivateImplClass);
1204

1205
                var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics);
1206
                Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName);
P
Pilchie 已提交
1207

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
                // Heuristics and well-known member availability determine the existence
                // of this helper.  Rather than reproduce that (language-specific) logic here,
                // we simply check for the information we really want - whether the helper is
                // available.
                if (stringHashMethodRef != null)
                {
                    // static uint ComputeStringHash(string s)
                    // pop 1 (s)
                    // push 1 (uint return value)
                    // stackAdjustment = (pushCount - popCount) = 0
P
Pilchie 已提交
1218

1219 1220 1221
                    _builder.EmitLoad(key);
                    _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
                    _builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics);
P
Pilchie 已提交
1222

1223
                    var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32);
1224
                    keyHash = AllocateTemp(UInt32Type, syntaxNode);
P
Pilchie 已提交
1225

1226
                    _builder.EmitLocalStore(keyHash);
1227
                }
P
Pilchie 已提交
1228 1229
            }

1230
            Cci.IReference stringEqualityMethodRef = _module.Translate(switchStatement.StringEquality, syntaxNode, _diagnostics);
P
Pilchie 已提交
1231

1232
            Cci.IMethodReference stringLengthRef = null;
1233
            var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol;
P
Pilchie 已提交
1234 1235
            if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError)
            {
1236
                stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics);
P
Pilchie 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245
            }

            SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate =
                (keyArg, stringConstant, targetLabel) =>
                {
                    if (stringConstant == ConstantValue.Null)
                    {
                        // if (key == null)
                        //      goto targetLabel
1246 1247
                        _builder.EmitLoad(keyArg);
                        _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
P
Pilchie 已提交
1248 1249 1250 1251 1252 1253 1254
                    }
                    else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null)
                    {
                        // if (key != null && key.Length == 0)
                        //      goto targetLabel

                        object skipToNext = new object();
1255 1256
                        _builder.EmitLoad(keyArg);
                        _builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue);
P
Pilchie 已提交
1257

1258
                        _builder.EmitLoad(keyArg);
P
Pilchie 已提交
1259
                        // Stack: key --> length
1260
                        _builder.EmitOpCode(ILOpCode.Call, 0);
P
Pilchie 已提交
1261
                        var diag = DiagnosticBag.GetInstance();
1262
                        _builder.EmitToken(stringLengthRef, null, diag);
P
Pilchie 已提交
1263 1264 1265
                        Debug.Assert(diag.IsEmptyWithoutResolution);
                        diag.Free();

1266 1267
                        _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue);
                        _builder.MarkLabel(skipToNext);
P
Pilchie 已提交
1268 1269 1270 1271 1272 1273 1274
                    }
                    else
                    {
                        this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef);
                    }
                };

1275
            _builder.EmitStringSwitchJumpTable(
P
Pilchie 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
                caseLabels: switchCaseLabels,
                fallThroughLabel: fallThroughLabel,
                key: key,
                keyHash: keyHash,
                emitStringCondBranchDelegate: emitStringCondBranchDelegate,
                computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash);

            if (keyHash != null)
            {
                FreeTemp(keyHash);
            }
        }

        /// <summary>
        /// Delegate to emit string compare call and conditional branch based on the compare result.
        /// </summary>
        /// <param name="key">Key to compare</param>
        /// <param name="syntaxNode">Node for diagnostics.</param>
        /// <param name="stringConstant">Case constant to compare the key against</param>
        /// <param name="targetLabel">Target label to branch to if key = stringConstant</param>
        /// <param name="stringEqualityMethodRef">String equality method</param>
1297
        private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef)
P
Pilchie 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
        {
            // Emit compare and branch:

            // if (key == stringConstant)
            //      goto targetLabel;

            Debug.Assert(stringEqualityMethodRef != null);

#if DEBUG
            var assertDiagnostics = DiagnosticBag.GetInstance();
1308
            Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics));
P
Pilchie 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317
            assertDiagnostics.Free();
#endif

            // static bool String.Equals(string a, string b)
            // pop 2 (a, b)
            // push 1 (bool return value)

            // stackAdjustment = (pushCount - popCount) = -1

1318 1319 1320 1321
            _builder.EmitLoad(key);
            _builder.EmitConstantValue(stringConstant);
            _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1);
            _builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics);
P
Pilchie 已提交
1322 1323

            // Branch to targetLabel if String.Equals returned true.
1324
            _builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse);
P
Pilchie 已提交
1325 1326 1327
        }

        private void EmitSwitchBody(
1328
            ImmutableArray<LocalSymbol> locals,
P
Pilchie 已提交
1329 1330 1331 1332
            ImmutableArray<BoundSwitchSection> switchSections,
            GeneratedLabelSymbol breakLabel,
            CSharpSyntaxNode syntaxNode)
        {
1333
            var hasLocals = !locals.IsEmpty;
P
Pilchie 已提交
1334 1335 1336

            if (hasLocals)
            {
1337
                _builder.OpenLocalScope();
P
Pilchie 已提交
1338

1339
                foreach (var local in locals)
P
Pilchie 已提交
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
                {
                    DefineLocal(local, syntaxNode);
                }
            }

            foreach (var section in switchSections)
            {
                EmitSwitchSection(section);
            }

1350
            _builder.MarkLabel(breakLabel);
P
Pilchie 已提交
1351 1352 1353

            if (hasLocals)
            {
1354
                _builder.CloseLocalScope();
P
Pilchie 已提交
1355 1356 1357 1358 1359
            }
        }

        private void EmitSwitchSection(BoundSwitchSection switchSection)
        {
N
Neal Gafter 已提交
1360
            foreach (var boundSwitchLabel in switchSection.SwitchLabels)
P
Pilchie 已提交
1361
            {
1362
                _builder.MarkLabel(boundSwitchLabel.Label);
P
Pilchie 已提交
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
            }

            foreach (var statement in switchSection.Statements)
            {
                EmitStatement(statement);
            }
        }

        /// <summary>
        /// Gets already declared and initialized local.
        /// </summary>
        private LocalDefinition GetLocal(BoundLocal localExpression)
        {
            var symbol = localExpression.LocalSymbol;
            return GetLocal(symbol);
        }

        private LocalDefinition GetLocal(LocalSymbol symbol)
        {
1382
            return _builder.LocalSlotManager.GetLocal(symbol);
P
Pilchie 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391
        }

        private LocalDefinition DefineLocal(LocalSymbol local, CSharpSyntaxNode syntaxNode)
        {
            var transformFlags = default(ImmutableArray<TypedConstant>);
            bool hasDynamic = local.Type.ContainsDynamic();
            var isDynamicSourceLocal = hasDynamic && !local.IsCompilerGenerated;
            if (isDynamicSourceLocal)
            {
1392
                NamedTypeSymbol booleanType = _module.Compilation.GetSpecialType(SpecialType.System_Boolean);
P
Pilchie 已提交
1393 1394 1395 1396 1397 1398
                transformFlags = CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, booleanType, 0, RefKind.None);
            }

            if (local.IsConst)
            {
                Debug.Assert(local.HasConstantValue);
1399
                MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics);
P
Pilchie 已提交
1400
                LocalConstantDefinition localConstantDef = new LocalConstantDefinition(local.Name, local.Locations.FirstOrDefault() ?? Location.None, compileTimeValue, isDynamicSourceLocal, transformFlags);
1401
                _builder.AddLocalConstantToScope(localConstantDef);
P
Pilchie 已提交
1402 1403
                return null;
            }
1404 1405

            if (IsStackLocal(local))
P
Pilchie 已提交
1406 1407 1408 1409
            {
                return null;
            }

1410
            LocalSlotConstraints constraints;
1411
            Cci.ITypeReference translatedType;
P
Pilchie 已提交
1412

1413
            if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case.
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
            {
                Debug.Assert(local.RefKind == RefKind.None);
                Debug.Assert(local.Type.IsPointerType());

                constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
                PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type;
                TypeSymbol pointedAtType = pointerType.PointedAtType;

                // We can't declare a reference to void, so if the pointed-at type is void, use native int
                // (represented here by IntPtr) instead.
                translatedType = pointedAtType.SpecialType == SpecialType.System_Void
1425 1426
                    ? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics)
                    : _module.Translate(pointedAtType, syntaxNode, _diagnostics);
1427 1428 1429 1430 1431
            }
            else
            {
                constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
                    (local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None);
1432
                translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics);
1433
            }
P
Pilchie 已提交
1434

1435 1436
            // Even though we don't need the token immediately, we will need it later when signature for the local is emitted.
            // Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc).
1437
            _module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics);
1438

1439 1440 1441
            LocalDebugId localId;
            var name = GetLocalDebugName(local, out localId);

1442
            var localDef = _builder.LocalSlotManager.DeclareLocal(
1443 1444 1445
                type: translatedType,
                symbol: local,
                name: name,
1446 1447 1448
                kind: local.SynthesizedKind,
                id: localId,
                pdbAttributes: local.SynthesizedKind.PdbAttributes(),
1449 1450
                constraints: constraints,
                isDynamic: isDynamicSourceLocal,
1451
                dynamicTransformFlags: transformFlags,
V
vsadov 已提交
1452
                isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release));
1453

1454 1455
            // If named, add it to the local debug scope.
            if (localDef.Name != null)
1456
            {
1457
                _builder.AddLocalToScope(localDef);
1458
            }
P
Pilchie 已提交
1459

1460 1461 1462
            return localDef;
        }

P
Pilchie 已提交
1463
        /// <summary>
1464
        /// Gets the name and id of the local that are going to be generated into the debug metadata.
1465
        /// </summary>
1466
        private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId)
P
Pilchie 已提交
1467
        {
1468 1469 1470
            localId = LocalDebugId.None;

            if (local.IsImportedFromMetadata)
1471 1472 1473
            {
                return local.Name;
            }
P
Pilchie 已提交
1474

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
            var localKind = local.SynthesizedKind;

            // only user-defined locals should be named during lowering:
            Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined));

            if (!localKind.IsLongLived())
            {
                return null;
            }

V
vsadov 已提交
1485
            if (_ilEmitStyle == ILEmitStyle.Debug)
1486 1487
            {
                var syntax = local.GetDeclaratorSyntax();
1488
                int syntaxOffset = _method.CalculateLocalSyntaxOffset(syntax.SpanStart, syntax.SyntaxTree);
1489

1490
                int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset);
1491 1492 1493 1494 1495 1496 1497

                // user-defined locals should have 0 ordinal:
                Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined);

                localId = new LocalDebugId(syntaxOffset, ordinal);
            }

1498
            return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId);
1499 1500 1501
        }

        private bool IsSlotReusable(LocalSymbol local)
P
Pilchie 已提交
1502
        {
V
vsadov 已提交
1503
            return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release);
P
Pilchie 已提交
1504 1505 1506 1507 1508 1509 1510
        }

        /// <summary>
        /// Releases a local.
        /// </summary>
        private void FreeLocal(LocalSymbol local)
        {
1511 1512
            // TODO: releasing named locals is NYI.
            if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local))
P
Pilchie 已提交
1513
            {
1514
                _builder.LocalSlotManager.FreeLocal(local);
P
Pilchie 已提交
1515 1516 1517 1518 1519 1520
            }
        }

        /// <summary>
        /// Allocates a temp without identity.
        /// </summary>
1521
        private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None)
P
Pilchie 已提交
1522
        {
1523 1524
            return _builder.LocalSlotManager.AllocateSlot(
                _module.Translate(type, syntaxNode, _diagnostics),
1525
                slotConstraints);
P
Pilchie 已提交
1526 1527 1528 1529 1530 1531 1532
        }

        /// <summary>
        /// Frees a temp.
        /// </summary>
        private void FreeTemp(LocalDefinition temp)
        {
1533
            _builder.LocalSlotManager.FreeSlot(temp);
P
Pilchie 已提交
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
        }

        /// <summary>
        /// Frees an optional temp.
        /// </summary>
        private void FreeOptTemp(LocalDefinition temp)
        {
            if (temp != null)
            {
                FreeTemp(temp);
            }
        }

        /// <summary>
        /// Clones all labels used in a finally block.
        /// This allows creating an emittable clone of finally.
        /// It is safe to do because no branches can go in or out of the finally handler.
        /// </summary>
1552
        private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
P
Pilchie 已提交
1553
        {
1554
            private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones;
P
Pilchie 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575

            private FinallyCloner() { }

            /// <summary>
            /// The argument is BoundTryStatement (and not a BoundBlock) specifically 
            /// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches.
            /// </summary>
            public static BoundBlock MakeFinallyClone(BoundTryStatement node)
            {
                var cloner = new FinallyCloner();
                return (BoundBlock)cloner.Visit(node.FinallyBlockOpt);
            }

            public override BoundNode VisitLabelStatement(BoundLabelStatement node)
            {
                return node.Update(GetLabelClone(node.Label));
            }

            public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
            {
                var breakLabelClone = GetLabelClone(node.BreakLabel);
1576
                var preambleOpt = (BoundStatement)this.Visit(node.LoweredPreambleOpt);
P
Pilchie 已提交
1577 1578

                // expressions do not contain labels or branches
N
Neal Gafter 已提交
1579
                BoundExpression boundExpression = node.Expression;
P
Pilchie 已提交
1580
                ImmutableArray<BoundSwitchSection> switchSections = (ImmutableArray<BoundSwitchSection>)this.VisitList(node.SwitchSections);
1581
                return node.Update(preambleOpt, boundExpression, node.ConstantTargetOpt, node.InnerLocals, node.InnerLocalFunctions, switchSections, breakLabelClone, node.StringEquality);
P
Pilchie 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
            }

            public override BoundNode VisitSwitchLabel(BoundSwitchLabel node)
            {
                var labelClone = GetLabelClone(node.Label);

                // expressions do not contain labels or branches
                BoundExpression expressionOpt = node.ExpressionOpt;
                return node.Update(labelClone, expressionOpt);
            }

            public override BoundNode VisitGotoStatement(BoundGotoStatement node)
            {
                var labelClone = GetLabelClone(node.Label);

                // expressions do not contain labels or branches
                BoundExpression caseExpressionOpt = node.CaseExpressionOpt;
                // expressions do not contain labels or branches
                BoundLabel labelExpressionOpt = node.LabelExpressionOpt;

                return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt);
            }

            public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
            {
                var labelClone = GetLabelClone(node.Label);

                // expressions do not contain labels or branches
                BoundExpression condition = node.Condition;

                return node.Update(condition, node.JumpIfTrue, labelClone);
            }

            public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
            {
                // expressions do not contain labels or branches
                return node;
            }

            private GeneratedLabelSymbol GetLabelClone(LabelSymbol label)
            {
1623
                var labelClones = _labelClones;
P
Pilchie 已提交
1624 1625
                if (labelClones == null)
                {
1626
                    _labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>();
P
Pilchie 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
                }

                GeneratedLabelSymbol clone;
                if (!labelClones.TryGetValue(label, out clone))
                {
                    clone = new GeneratedLabelSymbol("cloned_" + label.Name);
                    labelClones.Add(label, clone);
                }

                return clone;
            }
        }
    }
}