/// <summary> /// Produce assignment of the input expression. This method is also responsible for assigning /// variables for some pattern-matching temps that can be shared with user variables. /// </summary> protected BoundDecisionDag ShareTempsAndEvaluateInput( BoundExpression loweredInput, BoundDecisionDag decisionDag, Action <BoundExpression> addCode, out BoundExpression savedInputExpression) { var inputDagTemp = InputTemp(loweredInput); if (loweredInput.Kind == BoundKind.Local || loweredInput.Kind == BoundKind.Parameter) { // If we're switching on a local variable and there is no when clause (checked by the caller), // we assume the value of the local variable does not change during the execution of the // decision automaton and we just reuse the local variable when we need the input expression. // It is possible for this assumption to be violated by a side-effecting Deconstruct that // modifies the local variable which has been captured in a lambda. Since the language assumes // that functions called by pattern-matching are idempotent and not side-effecting, we feel // justified in taking this assumption in the compiler too. bool tempAssigned = _tempAllocator.TrySetTemp(inputDagTemp, loweredInput); Debug.Assert(tempAssigned); } foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes) { if (node is BoundWhenDecisionDagNode w) { // We share a slot for a user-declared pattern-matching variable with a pattern temp if there // is no user-written when-clause that could modify the variable before the matching // automaton is done with it (checked by the caller). foreach (BoundPatternBinding binding in w.Bindings) { if (binding.VariableAccess is BoundLocal l) { Debug.Assert(l.LocalSymbol.DeclarationKind == LocalDeclarationKind.PatternVariable); _ = _tempAllocator.TrySetTemp(binding.TempContainingValue, binding.VariableAccess); } } } } if (loweredInput.Type.IsTupleType && loweredInput.Syntax.Kind() == SyntaxKind.TupleExpression && loweredInput is BoundObjectCreationExpression expr && !decisionDag.TopologicallySortedNodes.Any(n => usesOriginalInput(n))) { // If the switch governing expression is a tuple literal whose whole value is not used anywhere, // (though perhaps its component parts are used), then we can save the component parts // and assign them into temps (or perhaps user variables) to avoid the creation of // the tuple altogether. decisionDag = RewriteTupleInput(decisionDag, expr, addCode, out savedInputExpression); }
private void CheckSwitchErrors( SwitchStatementSyntax node, BoundExpression boundSwitchGoverningExpression, ref ImmutableArray<BoundSwitchSection> switchSections, BoundDecisionDag decisionDag, DiagnosticBag diagnostics) { var reachableLabels = decisionDag.ReachableLabels; bool isSubsumed(BoundSwitchLabel switchLabel) { return !reachableLabels.Contains(switchLabel.Label); } // If no switch sections are subsumed, just return if (!switchSections.Any(s => s.SwitchLabels.Any(l => isSubsumed(l)))) { return; } var sectionBuilder = ArrayBuilder<BoundSwitchSection>.GetInstance(switchSections.Length); foreach (var oldSection in switchSections) { var labelBuilder = ArrayBuilder<BoundSwitchLabel>.GetInstance(oldSection.SwitchLabels.Length); foreach (var label in oldSection.SwitchLabels) { var newLabel = label; if (!label.HasErrors && isSubsumed(label) && label.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel) { var syntax = label.Syntax; switch (syntax) { case CasePatternSwitchLabelSyntax p: if (!p.Pattern.HasErrors) { diagnostics.Add(ErrorCode.ERR_SwitchCaseSubsumed, p.Pattern.Location); } break; case CaseSwitchLabelSyntax p: if (label.Pattern is BoundConstantPattern cp && !cp.ConstantValue.IsBad && FindMatchingSwitchCaseLabel(cp.ConstantValue, p) != label.Label) { // We use the traditional diagnostic when possible diagnostics.Add(ErrorCode.ERR_DuplicateCaseLabel, syntax.Location, cp.ConstantValue.GetValueToDisplay()); } else if (!label.Pattern.HasErrors) { diagnostics.Add(ErrorCode.ERR_SwitchCaseSubsumed, p.Value.Location); } break;
private void ComputeLabelSet(BoundDecisionDag decisionDag) { // Nodes with more than one predecessor are assigned a label var hasPredecessor = PooledHashSet <BoundDecisionDagNode> .GetInstance(); foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes) { switch (node) { case BoundWhenDecisionDagNode w: GetDagNodeLabel(node); if (w.WhenFalse != null) { GetDagNodeLabel(w.WhenFalse); } break; case BoundLeafDecisionDagNode d: // Leaf can branch directly to the target _dagNodeLabels[node] = d.Label; break; case BoundEvaluationDecisionDagNode e: notePredecessor(e.Next); break; case BoundTestDecisionDagNode p: notePredecessor(p.WhenTrue); notePredecessor(p.WhenFalse); break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } } hasPredecessor.Free(); return; void notePredecessor(BoundDecisionDagNode successor) { if (successor != null && !hasPredecessor.Add(successor)) { GetDagNodeLabel(successor); } } }
/// <summary> /// Bind the switch statement, reporting in the process any switch labels that are subsumed by previous cases. /// </summary> internal override BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, DiagnosticBag diagnostics) { Debug.Assert(SwitchSyntax.Equals(node)); if (node.Sections.Count == 0) { diagnostics.Add(ErrorCode.WRN_EmptySwitch, node.OpenBraceToken.GetLocation()); } // Bind switch expression and set the switch governing type. BoundExpression boundSwitchGoverningExpression = SwitchGoverningExpression; diagnostics.AddRange(SwitchGoverningDiagnostics); ImmutableArray<BoundSwitchSection> switchSections = BindSwitchSections(originalBinder, diagnostics, out BoundSwitchLabel defaultLabel); ImmutableArray<LocalSymbol> locals = GetDeclaredLocalsForScope(node); ImmutableArray<LocalFunctionSymbol> functions = GetDeclaredLocalFunctionsForScope(node); BoundDecisionDag decisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchStatement( compilation: this.Compilation, syntax: node, switchGoverningExpression: boundSwitchGoverningExpression, switchSections: switchSections, // If there is no explicit default label, the default action is to break out of the switch defaultLabel: defaultLabel?.Label ?? BreakLabel, diagnostics); // Report subsumption errors, but ignore the input's constant value for that. CheckSwitchErrors(node, boundSwitchGoverningExpression, ref switchSections, decisionDag, diagnostics); // When the input is constant, we use that to reshape the decision dag that is returned // so that flow analysis will see that some of the cases may be unreachable. decisionDag = decisionDag.SimplifyDecisionDagIfConstantInput(boundSwitchGoverningExpression); return new BoundSwitchStatement( syntax: node, expression: boundSwitchGoverningExpression, innerLocals: locals, innerLocalFunctions: functions, switchSections: switchSections, defaultLabel: defaultLabel, breakLabel: this.BreakLabel, decisionDag: decisionDag); }
public BoundExpression LowerIsPattern( BoundIsPatternExpression isPatternExpression, BoundPattern pattern, CSharpCompilation compilation, DiagnosticBag diagnostics) { BoundDecisionDag decisionDag = isPatternExpression.DecisionDag; LabelSymbol whenTrueLabel = isPatternExpression.WhenTrueLabel; LabelSymbol whenFalseLabel = isPatternExpression.WhenFalseLabel; BoundExpression loweredInput = _localRewriter.VisitExpression(isPatternExpression.Expression); // The optimization of sharing pattern-matching temps with user variables can always apply to // an is-pattern expression because there is no when clause that could possibly intervene during // the execution of the pattern-matching automaton and change one of those variables. decisionDag = ShareTempsAndEvaluateInput(loweredInput, decisionDag, expr => _sideEffectBuilder.Add(expr), out _); var node = decisionDag.RootNode; // We follow the "good" path in the decision dag. We depend on it being nicely linear in structure. // If we add "or" patterns that assumption breaks down. while (node.Kind != BoundKind.LeafDecisionDagNode && node.Kind != BoundKind.WhenDecisionDagNode) { switch (node) { case BoundEvaluationDecisionDagNode evalNode: { LowerOneTest(evalNode.Evaluation); node = evalNode.Next; } break; case BoundTestDecisionDagNode testNode: { Debug.Assert(testNode.WhenFalse is BoundLeafDecisionDagNode x && x.Label == whenFalseLabel); if (testNode.WhenTrue is BoundEvaluationDecisionDagNode e && TryLowerTypeTestAndCast(testNode.Test, e.Evaluation, out BoundExpression sideEffect, out BoundExpression testExpression)) { _sideEffectBuilder.Add(sideEffect); AddConjunct(testExpression); node = e.Next; }
private BoundStatement LowerSwitchStatement(BoundSwitchStatement node) { _factory.Syntax = node.Syntax; var result = ArrayBuilder <BoundStatement> .GetInstance(); var outerVariables = ArrayBuilder <LocalSymbol> .GetInstance(); var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression); if (!node.WasCompilerGenerated && _localRewriter.Instrument) { // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the expression are being executed. var instrumentedExpression = _localRewriter._instrumenter.InstrumentSwitchStatementExpression(node, loweredSwitchGoverningExpression, _factory); if (loweredSwitchGoverningExpression.ConstantValue == null) { loweredSwitchGoverningExpression = instrumentedExpression; } else { // If the expression is a constant, we leave it alone (the decision dag lowering code needs // to see that constant). But we add an additional leading statement with the instrumented expression. result.Add(_factory.ExpressionStatement(instrumentedExpression)); } } // The set of variables attached to the outer block outerVariables.AddRange(node.InnerLocals); // Evaluate the input and set up sharing for dag temps with user variables BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput(node.DecisionDag, loweredSwitchGoverningExpression, result, out _); // lower the decision dag. (ImmutableArray <BoundStatement> loweredDag, ImmutableDictionary <SyntaxNode, ImmutableArray <BoundStatement> > switchSections) = LowerDecisionDag(decisionDag); // then add the rest of the lowered dag that references that input result.Add(_factory.Block(loweredDag)); // A branch to the default label when no switch case matches is included in the // decision dag, so the code in `result` is unreachable at this point. // Lower each switch section. foreach (BoundSwitchSection section in node.SwitchSections) { _factory.Syntax = section.Syntax; var sectionBuilder = ArrayBuilder <BoundStatement> .GetInstance(); sectionBuilder.AddRange(switchSections[section.Syntax]); foreach (BoundSwitchLabel switchLabel in section.SwitchLabels) { sectionBuilder.Add(_factory.Label(switchLabel.Label)); } // Add the translated body of the switch section sectionBuilder.AddRange(_localRewriter.VisitList(section.Statements)); // By the semantics of the switch statement, the end of each section is required to be unreachable. // So we can just seal the block and there is no need to follow it by anything. ImmutableArray <BoundStatement> statements = sectionBuilder.ToImmutableAndFree(); if (section.Locals.IsEmpty) { result.Add(_factory.StatementList(statements)); } else { // Lifetime of these locals is expanded to the entire switch body, as it is possible to capture // them in a different section by using a local function as an intermediary. outerVariables.AddRange(section.Locals); // Note the language scope of the locals, even though they are included for the purposes of // lifetime analysis in the enclosing scope. result.Add(new BoundScope(section.Syntax, section.Locals, statements)); } } // Dispatch temps are in scope throughout the switch statement, as they are used // both in the dispatch section to hold temporary values from the translation of // the decision dag, and in the branches where the temp values are assigned to the // pattern variables of matched patterns. outerVariables.AddRange(_tempAllocator.AllTemps()); _factory.Syntax = node.Syntax; result.Add(_factory.Label(node.BreakLabel)); BoundStatement translatedSwitch = _factory.Block(outerVariables.ToImmutableAndFree(), node.InnerLocalFunctions, result.ToImmutableAndFree()); // Only add instrumentation (such as a sequence point) if the node is not compiler-generated. if (!node.WasCompilerGenerated && _localRewriter.Instrument) { translatedSwitch = _localRewriter._instrumenter.InstrumentSwitchStatement(node, translatedSwitch); } return(translatedSwitch); }
private BoundExpression LowerSwitchExpression(BoundSwitchExpression node) { _factory.Syntax = node.Syntax; var result = ArrayBuilder <BoundStatement> .GetInstance(); var outerVariables = ArrayBuilder <LocalSymbol> .GetInstance(); var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression); BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput( node.DecisionDag, loweredSwitchGoverningExpression, result, out BoundExpression savedInputExpression); Debug.Assert(savedInputExpression != null); // lower the decision dag. (ImmutableArray <BoundStatement> loweredDag, ImmutableDictionary <SyntaxNode, ImmutableArray <BoundStatement> > switchSections) = LowerDecisionDag(decisionDag); // then add the rest of the lowered dag that references that input result.Add(_factory.Block(loweredDag)); // A branch to the default label when no switch case matches is included in the // decision tree, so the code in result is unreachable at this point. // Lower each switch expression arm LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.SwitchCasePatternMatching); LabelSymbol afterSwitchExpression = _factory.GenerateLabel("afterSwitchExpression"); foreach (BoundSwitchExpressionArm arm in node.SwitchArms) { _factory.Syntax = arm.Syntax; var sectionBuilder = ArrayBuilder <BoundStatement> .GetInstance(); sectionBuilder.AddRange(switchSections[arm.Syntax]); sectionBuilder.Add(_factory.Label(arm.Label)); sectionBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _localRewriter.VisitExpression(arm.Value))); sectionBuilder.Add(_factory.Goto(afterSwitchExpression)); var statements = sectionBuilder.ToImmutableAndFree(); if (arm.Locals.IsEmpty) { result.Add(_factory.StatementList(statements)); } else { // Lifetime of these locals is expanded to the entire switch body, as it is possible to // share them as temps in the decision dag. outerVariables.AddRange(arm.Locals); // Note the language scope of the locals, even though they are included for the purposes of // lifetime analysis in the enclosing scope. result.Add(new BoundScope(arm.Syntax, arm.Locals, statements)); } } _factory.Syntax = node.Syntax; if (node.DefaultLabel != null) { result.Add(_factory.Label(node.DefaultLabel)); var objectType = _factory.SpecialType(SpecialType.System_Object); var thrownExpression = (implicitConversionExists(savedInputExpression, objectType) && _factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, isOptional: true) is MethodSymbol exception1) ? _factory.New(exception1, _factory.Convert(objectType, savedInputExpression)) : (_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, isOptional: true) is MethodSymbol exception0) ? _factory.New(exception0) : _factory.New(_factory.WellKnownMethod(WellKnownMember.System_InvalidOperationException__ctor)); result.Add(_factory.Throw(thrownExpression)); } result.Add(_factory.Label(afterSwitchExpression)); outerVariables.Add(resultTemp); outerVariables.AddRange(_tempAllocator.AllTemps()); return(_factory.SpillSequence(outerVariables.ToImmutableAndFree(), result.ToImmutableAndFree(), _factory.Local(resultTemp))); bool implicitConversionExists(BoundExpression expression, TypeSymbol type) { HashSet <DiagnosticInfo> discarded = null; Conversion c = _localRewriter._compilation.Conversions.ClassifyConversionFromExpression(expression, type, ref discarded); return(c.IsImplicit); } }
private void LowerDecisionDagCore(BoundDecisionDag decisionDag) { ImmutableArray <BoundDecisionDagNode> sortedNodes = decisionDag.TopologicallySortedNodes; var firstNode = sortedNodes[0]; switch (firstNode) { case BoundWhenDecisionDagNode _: case BoundLeafDecisionDagNode _: // If the first node is a leaf or when clause rather than the code for the // lowered decision dag, jump there to start. _loweredDecisionDag.Add(_factory.Goto(GetDagNodeLabel(firstNode))); break; } // Code for each when clause goes in the separate code section for its switch section. foreach (BoundDecisionDagNode node in sortedNodes) { if (node is BoundWhenDecisionDagNode w) { LowerWhenClause(w); } } ImmutableArray <BoundDecisionDagNode> nodesToLower = sortedNodes.WhereAsArray(n => n.Kind != BoundKind.WhenDecisionDagNode && n.Kind != BoundKind.LeafDecisionDagNode); var loweredNodes = PooledHashSet <BoundDecisionDagNode> .GetInstance(); for (int i = 0, length = nodesToLower.Length; i < length; i++) { BoundDecisionDagNode node = nodesToLower[i]; if (loweredNodes.Contains(node)) { Debug.Assert(!_dagNodeLabels.TryGetValue(node, out _)); continue; } if (this._dagNodeLabels.TryGetValue(node, out LabelSymbol label)) { _loweredDecisionDag.Add(_factory.Label(label)); } // If we can generate an IL switch instruction, do so if (GenerateSwitchDispatch(node, loweredNodes)) { continue; } // If we can generate a type test and cast more efficiently as an `is` followed by a null check, do so if (GenerateTypeTestAndCast(node, loweredNodes, nodesToLower, i)) { continue; } // We pass the node that will follow so we can permit a test to fall through if appropriate BoundDecisionDagNode nextNode = ((i + 1) < length) ? nodesToLower[i + 1] : null; if (nextNode != null && loweredNodes.Contains(nextNode)) { nextNode = null; } LowerDecisionDagNode(node, nextNode); } loweredNodes.Free(); }
/// <summary> /// Lower the given nodes into _loweredDecisionDag. Should only be called once per instance of this. /// </summary> protected (ImmutableArray <BoundStatement> loweredDag, ImmutableDictionary <SyntaxNode, ImmutableArray <BoundStatement> > switchSections) LowerDecisionDag(BoundDecisionDag decisionDag) { Debug.Assert(this._loweredDecisionDag.IsEmpty()); ComputeLabelSet(decisionDag); LowerDecisionDagCore(decisionDag); ImmutableArray <BoundStatement> loweredDag = this._loweredDecisionDag.ToImmutableAndFree(); ImmutableDictionary <SyntaxNode, ImmutableArray <BoundStatement> > switchSections = this._switchArms.ToImmutableDictionary(kv => kv.Key, kv => kv.Value.ToImmutableAndFree()); this._switchArms.Clear(); return(loweredDag, switchSections); }
/// <summary> /// Build the decision dag, giving an error if some cases are subsumed and a warning if the switch expression is not exhaustive. /// </summary> /// <param name="node"></param> /// <param name="boundInputExpression"></param> /// <param name="switchArms"></param> /// <param name="decisionDag"></param> /// <param name="diagnostics"></param> /// <returns>true if there was a non-exhaustive warning reported</returns> private bool CheckSwitchExpressionExhaustive( SwitchExpressionSyntax node, BoundExpression boundInputExpression, ImmutableArray <BoundSwitchExpressionArm> switchArms, out BoundDecisionDag decisionDag, out LabelSymbol defaultLabel, DiagnosticBag diagnostics) { defaultLabel = new GeneratedLabelSymbol("default"); decisionDag = DecisionDagBuilder.CreateDecisionDagForSwitchExpression(this.Compilation, node, boundInputExpression, switchArms, defaultLabel, diagnostics); var reachableLabels = decisionDag.ReachableLabels; foreach (BoundSwitchExpressionArm arm in switchArms) { if (!reachableLabels.Contains(arm.Label)) { diagnostics.Add(ErrorCode.ERR_SwitchArmSubsumed, arm.Pattern.Syntax.Location); } } if (!reachableLabels.Contains(defaultLabel)) { // switch expression is exhaustive; no default label needed. defaultLabel = null; return(false); } // We only report exhaustive warnings when the default label is reachable through some series of // tests that do not include a test in which the value is know to be null. Handling paths with // nulls is the job of the nullable walker. foreach (var n in TopologicalSort.IterativeSort <BoundDecisionDagNode>(new[] { decisionDag.RootNode }, nonNullSuccessors)) { if (n is BoundLeafDecisionDagNode leaf && leaf.Label == defaultLabel) { diagnostics.Add(ErrorCode.WRN_SwitchExpressionNotExhaustive, node.SwitchKeyword.GetLocation()); return(true); } } return(false); ImmutableArray <BoundDecisionDagNode> nonNullSuccessors(BoundDecisionDagNode n) { switch (n) { case BoundTestDecisionDagNode p: switch (p.Test) { case BoundDagNonNullTest t: // checks that the input is not null return(ImmutableArray.Create(p.WhenTrue)); case BoundDagNullTest t: // checks that the input is null return(ImmutableArray.Create(p.WhenFalse)); default: return(BoundDecisionDag.Successors(n)); } default: return(BoundDecisionDag.Successors(n)); } } }