public override Procedure VisitProcedure(Procedure node)
        {
            Debug.Assert(civlTypeChecker.procToYieldingProc.ContainsKey(node));
            if (!procToDuplicate.ContainsKey(node))
            {
                YieldingProc yieldingProc = civlTypeChecker.procToYieldingProc[node];
                Debug.Assert(layerNum <= yieldingProc.upperLayer);

                Procedure proc = (Procedure)node.Clone();
                proc.Name      = civlTypeChecker.AddNamePrefix($"{node.Name}_{layerNum}");
                proc.InParams  = this.VisitVariableSeq(node.InParams);
                proc.OutParams = this.VisitVariableSeq(node.OutParams);
                proc.Requires  = this.VisitRequiresSeq(node.Requires);
                proc.Ensures   = this.VisitEnsuresSeq(node.Ensures);
                if (yieldingProc is MoverProc moverProc && yieldingProc.upperLayer == layerNum)
                {
                    proc.Modifies = moverProc.modifiedGlobalVars.Select(g => Expr.Ident(g)).ToList();
                }
                else
                {
                    proc.Modifies = civlTypeChecker.GlobalVariables.Select(v => Expr.Ident(v)).ToList();
                    yieldingProcs.Add(proc);
                }

                procToDuplicate[node] = proc;
                absyMap[proc]         = node;
            }
Exemple #2
0
        public static void AddCheckers(CivlTypeChecker civlTypeChecker)
        {
            foreach (var action in civlTypeChecker.AllAtomicActions.Where(a => a.HasPendingAsyncs))
            {
                var requires = action.gate.Select(g => new Requires(false, g.Expr)).ToList();
                var cmds     = new List <Cmd>
                {
                    CmdHelper.CallCmd(
                        action.proc,
                        action.impl.InParams.Select(Expr.Ident).ToList <Expr>(),
                        action.impl.OutParams.Select(Expr.Ident).ToList())
                };
                var blocks = new List <Block>()
                {
                    new Block(Token.NoToken, "init", cmds, CmdHelper.ReturnCmd)
                };

                var PAs     = Expr.Ident(action.impl.OutParams.Last(p => p.TypedIdent.Type.Equals(civlTypeChecker.pendingAsyncMultisetType)));
                var paBound = civlTypeChecker.BoundVariable("pa", civlTypeChecker.pendingAsyncType);
                var pa      = Expr.Ident(paBound);

                var nonnegativeExpr =
                    new ForallExpr(Token.NoToken, new List <Variable> {
                    paBound
                },
                                   Expr.Ge(Expr.Select(PAs, pa), Expr.Literal(0)));
                var correctTypeExpr = new ForallExpr(Token.NoToken, new List <Variable> {
                    paBound
                },
                                                     Expr.Imp(
                                                         Expr.Gt(Expr.Select(PAs, pa), Expr.Literal(0)),
                                                         Expr.Or(action.pendingAsyncs.Select(a => ExprHelper.FunctionCall(a.pendingAsyncCtor.membership, pa)))));
                var ensures = new List <Ensures>
                {
                    new Ensures(false, nonnegativeExpr)
                    {
                        ErrorData = $"Action {action.proc.Name} might create negative pending asyncs"
                    },
                    new Ensures(false, correctTypeExpr)
                    {
                        ErrorData = $"Action {action.proc.Name} might create undeclared pending asyncs"
                    },
                };

                CivlUtil.ResolveAndTypecheck(ensures);

                var proc = new Procedure(Token.NoToken, civlTypeChecker.AddNamePrefix($"PendingAsyncChecker_{action.proc.Name}"), new List <TypeVariable>(),
                                         action.impl.InParams, action.impl.OutParams,
                                         requires, action.proc.Modifies, ensures);
                var impl = new Implementation(Token.NoToken, proc.Name, proc.TypeParameters,
                                              proc.InParams, proc.OutParams, new List <Variable>(), blocks)
                {
                    Proc = proc
                };

                civlTypeChecker.program.AddTopLevelDeclaration(proc);
                civlTypeChecker.program.AddTopLevelDeclaration(impl);
            }
        }
Exemple #3
0
        private Block CreateInitialBlock(Implementation impl, List <Cmd> preconditions)
        {
            var initCmds = new List <Cmd>(preconditions);

            initCmds.AddRange(globalSnapshotInstrumentation.CreateInitCmds());
            initCmds.AddRange(refinementInstrumentation.CreateInitCmds());
            initCmds.AddRange(noninterferenceInstrumentation.CreateInitCmds(impl));
            return(BlockHelper.Block(civlTypeChecker.AddNamePrefix("init"), initCmds, new List <Block> {
                impl.Blocks[0]
            }));
        }
Exemple #4
0
        private static Tuple <Procedure, Implementation> GenerateAbstractionChecker(CivlTypeChecker civlTypeChecker, AtomicAction action, AtomicAction abs)
        {
            var requires = abs.gate.Select(g => new Requires(false, g.Expr)).ToList();
            // TODO: check frame computation
            var frame = new HashSet <Variable>(
                action.modifiedGlobalVars
                .Union(action.gateUsedGlobalVars)
                .Union(abs.modifiedGlobalVars)
                .Union(abs.gateUsedGlobalVars));
            var tr      = TransitionRelationComputation.Refinement(civlTypeChecker, abs, frame);
            var ensures = new List <Ensures> {
                new Ensures(false, tr)
                {
                    ErrorData = $"Abstraction {abs.proc.Name} does not summarize {action.proc.Name}"
                }
            };

            var        subst = InductiveSequentialization.GetSubstitution(action, abs);
            List <Cmd> cmds  = InductiveSequentialization.GetGateAsserts(action, subst,
                                                                         $"Abstraction {abs.proc.Name} fails gate of {action.proc.Name}").ToList <Cmd>();

            cmds.Add(
                CmdHelper.CallCmd(
                    action.proc,
                    abs.impl.InParams.Select(Expr.Ident).ToList <Expr>(),
                    abs.impl.OutParams.Select(Expr.Ident).ToList()
                    ));
            var blocks = new List <Block> {
                new Block(Token.NoToken, "init", cmds, CmdHelper.ReturnCmd)
            };

            var proc = new Procedure(
                Token.NoToken,
                civlTypeChecker.AddNamePrefix($"AbstractionCheck_{action.proc.Name}_{abs.proc.Name}"),
                new List <TypeVariable>(),
                abs.impl.InParams,
                abs.impl.OutParams,
                requires,
                action.proc.Modifies,
                ensures);
            var impl = new Implementation(
                Token.NoToken,
                proc.Name,
                new List <TypeVariable>(),
                proc.InParams,
                proc.OutParams,
                new List <Variable>(),
                blocks)
            {
                Proc = proc
            };

            return(Tuple.Create(proc, impl));
        }
Exemple #5
0
        private void AddChecker(string checkerName, List <Variable> inputs, List <Variable> outputs, List <Variable> locals,
                                List <Requires> requires, List <Ensures> ensures, List <Block> blocks)
        {
            checkerName = civlTypeChecker.AddNamePrefix(checkerName);
            Procedure proc = new Procedure(Token.NoToken, checkerName, new List <TypeVariable>(), inputs, outputs, requires,
                                           civlTypeChecker.GlobalVariables.Select(v => Expr.Ident(v)).ToList(), ensures);
            Implementation impl = new Implementation(Token.NoToken, checkerName, new List <TypeVariable>(), inputs, outputs,
                                                     locals, blocks);

            impl.Proc = proc;
            this.decls.Add(impl);
            this.decls.Add(proc);
        }
Exemple #6
0
        private YieldingProcInstrumentation(
            CivlTypeChecker civlTypeChecker,
            LinearPermissionInstrumentation linearPermissionInstrumentation,
            int layerNum,
            AbsyMap absyMap,
            Dictionary <CallCmd, Block> refinementBlocks)
        {
            this.civlTypeChecker = civlTypeChecker;
            this.layerNum        = layerNum;
            this.absyMap         = absyMap;
            this.linearPermissionInstrumentation = linearPermissionInstrumentation;
            this.refinementBlocks       = refinementBlocks;
            parallelCallAggregators     = new Dictionary <string, Procedure>();
            noninterferenceCheckerDecls = new List <Declaration>();

            var             linearTypeChecker = civlTypeChecker.linearTypeChecker;
            List <Variable> inputs            = new List <Variable>();

            foreach (string domainName in linearTypeChecker.linearDomains.Keys)
            {
                inputs.Add(linearTypeChecker.LinearDomainInFormal(domainName));
            }

            foreach (Variable g in civlTypeChecker.GlobalVariables)
            {
                inputs.Add(OldGlobalFormal(g));
            }

            wrapperNoninterferenceCheckerProc = new Procedure(Token.NoToken,
                                                              civlTypeChecker.AddNamePrefix($"Wrapper_NoninterferenceChecker_{layerNum}"), new List <TypeVariable>(),
                                                              inputs, new List <Variable>(), new List <Requires>(), new List <IdentifierExpr>(), new List <Ensures>());
            CivlUtil.AddInlineAttribute(wrapperNoninterferenceCheckerProc);

            // initialize globalSnapshotInstrumentation
            globalSnapshotInstrumentation = new GlobalSnapshotInstrumentation(civlTypeChecker);

            // initialize noninterferenceInstrumentation
            if (CommandLineOptions.Clo.TrustNoninterference)
            {
                noninterferenceInstrumentation = new NoneNoninterferenceInstrumentation();
            }
            else
            {
                noninterferenceInstrumentation = new SomeNoninterferenceInstrumentation(
                    civlTypeChecker,
                    linearTypeChecker,
                    linearPermissionInstrumentation,
                    globalSnapshotInstrumentation.OldGlobalMap,
                    wrapperNoninterferenceCheckerProc);
            }
        }
Exemple #7
0
        private void AddChecker(string checkerName, List <Variable> inputs, List <Variable> outputs, List <Variable> locals,
                                List <Requires> requires, List <Cmd> cmds)
        {
            checkerName = civlTypeChecker.AddNamePrefix(checkerName);
            var blocks = new List <Block> {
                BlockHelper.Block("init", cmds)
            };
            Procedure proc = DeclHelper.Procedure(checkerName, inputs, outputs, requires,
                                                  civlTypeChecker.GlobalVariables.Select(v => Expr.Ident(v)).ToList(), new List <Ensures>());
            Implementation impl = DeclHelper.Implementation(proc, inputs, outputs, locals, blocks);

            this.decls.Add(impl);
            this.decls.Add(proc);
        }
Exemple #8
0
        private Block CreateInitialBlock(Implementation impl, List <Cmd> preconditions)
        {
            var initCmds = new List <Cmd>(preconditions);

            initCmds.AddRange(globalSnapshotInstrumentation.CreateInitCmds());
            initCmds.AddRange(refinementInstrumentation.CreateInitCmds());
            initCmds.AddRange(noninterferenceInstrumentation.CreateInitCmds(impl));
            var gotoCmd = new GotoCmd(Token.NoToken, new List <String> {
                impl.Blocks[0].Label
            },
                                      new List <Block> {
                impl.Blocks[0]
            });

            return(new Block(Token.NoToken, civlTypeChecker.AddNamePrefix("init"), initCmds, gotoCmd));
        }
Exemple #9
0
        private static Tuple <Procedure, Implementation> GenerateAbstractionChecker(CivlTypeChecker civlTypeChecker, AtomicAction action, AtomicAction abs)
        {
            var requires = abs.gate.Select(g => new Requires(false, g.Expr)).ToList();
            // TODO: check frame computation
            var frame = new HashSet <Variable>(
                action.modifiedGlobalVars
                .Union(action.gateUsedGlobalVars)
                .Union(abs.modifiedGlobalVars)
                .Union(abs.gateUsedGlobalVars));

            var        subst = InductiveSequentialization.GetSubstitution(action, abs);
            List <Cmd> cmds  = InductiveSequentialization.GetGateAsserts(action, subst,
                                                                         $"Abstraction {abs.proc.Name} fails gate of {action.proc.Name}").ToList <Cmd>();

            cmds.Add(
                CmdHelper.CallCmd(
                    action.proc,
                    abs.impl.InParams,
                    abs.impl.OutParams
                    ));
            cmds.Add(
                CmdHelper.AssertCmd(
                    abs.proc.tok,
                    TransitionRelationComputation.Refinement(civlTypeChecker, abs, frame),
                    $"Abstraction {abs.proc.Name} does not summarize {action.proc.Name}"
                    ));

            var blocks = new List <Block> {
                BlockHelper.Block("init", cmds)
            };

            var proc = DeclHelper.Procedure(
                civlTypeChecker.AddNamePrefix($"AbstractionCheck_{action.proc.Name}_{abs.proc.Name}"),
                abs.impl.InParams,
                abs.impl.OutParams,
                requires,
                action.proc.Modifies,
                new List <Ensures>());
            var impl = DeclHelper.Implementation(
                proc,
                proc.InParams,
                proc.OutParams,
                new List <Variable>(),
                blocks);

            return(Tuple.Create(proc, impl));
        }
Exemple #10
0
        public static List <Declaration> CreateNoninterferenceCheckers(
            CivlTypeChecker civlTypeChecker,
            int layerNum,
            AbsyMap absyMap,
            DeclWithFormals decl,
            List <Variable> declLocalVariables)
        {
            var linearTypeChecker = civlTypeChecker.linearTypeChecker;
            Dictionary <string, Variable>   domainNameToHoleVar = new Dictionary <string, Variable>();
            Dictionary <Variable, Variable> localVarMap         = new Dictionary <Variable, Variable>();
            Dictionary <Variable, Expr>     map = new Dictionary <Variable, Expr>();
            List <Variable> locals = new List <Variable>();
            List <Variable> inputs = new List <Variable>();

            foreach (var domainName in linearTypeChecker.linearDomains.Keys)
            {
                var inParam = linearTypeChecker.LinearDomainInFormal(domainName);
                inputs.Add(inParam);
                domainNameToHoleVar[domainName] = inParam;
            }

            foreach (Variable local in declLocalVariables.Union(decl.InParams).Union(decl.OutParams))
            {
                var copy = CopyLocal(local);
                locals.Add(copy);
                localVarMap[local] = copy;
                map[local]         = Expr.Ident(copy);
            }

            Dictionary <Variable, Expr> oldLocalMap = new Dictionary <Variable, Expr>();
            Dictionary <Variable, Expr> assumeMap   = new Dictionary <Variable, Expr>(map);

            foreach (Variable g in civlTypeChecker.GlobalVariables)
            {
                var copy = OldGlobalLocal(civlTypeChecker, g);
                locals.Add(copy);
                oldLocalMap[g] = Expr.Ident(copy);
                Formal f = SnapshotGlobalFormal(civlTypeChecker, g);
                inputs.Add(f);
                assumeMap[g] = Expr.Ident(f);
            }

            var linearPermissionInstrumentation = new LinearPermissionInstrumentation(civlTypeChecker,
                                                                                      layerNum, absyMap, domainNameToHoleVar, localVarMap);
            List <YieldInfo> yieldInfos = null;
            string           noninterferenceCheckerName = null;

            if (decl is Implementation impl)
            {
                noninterferenceCheckerName = $"impl_{absyMap.Original(impl).Name}_{layerNum}";
                yieldInfos = CollectYields(civlTypeChecker, absyMap, layerNum, impl).Select(kv =>
                                                                                            new YieldInfo(linearPermissionInstrumentation.DisjointnessAssumeCmds(kv.Key, false), kv.Value)).ToList();
            }
            else if (decl is Procedure proc)
            {
                yieldInfos = new List <YieldInfo>();
                if (civlTypeChecker.procToYieldInvariant.ContainsKey(proc))
                {
                    noninterferenceCheckerName = $"yield_{proc.Name}";
                    if (proc.Requires.Count > 0)
                    {
                        var disjointnessCmds = linearPermissionInstrumentation.ProcDisjointnessAssumeCmds(proc, true);
                        var yieldPredicates  = proc.Requires.Select(requires =>
                                                                    requires.Free
                ? (PredicateCmd) new AssumeCmd(requires.tok, requires.Condition)
                : (PredicateCmd) new AssertCmd(requires.tok, requires.Condition)).ToList();
                        yieldInfos.Add(new YieldInfo(disjointnessCmds, yieldPredicates));
                    }
                }
                else
                {
                    noninterferenceCheckerName = $"proc_{absyMap.Original(proc).Name}_{layerNum}";
                    if (proc.Requires.Count > 0)
                    {
                        var entryDisjointnessCmds =
                            linearPermissionInstrumentation.ProcDisjointnessAssumeCmds(proc, true);
                        var entryYieldPredicates = proc.Requires.Select(requires =>
                                                                        requires.Free
                ? (PredicateCmd) new AssumeCmd(requires.tok, requires.Condition)
                : (PredicateCmd) new AssertCmd(requires.tok, requires.Condition)).ToList();
                        yieldInfos.Add(new YieldInfo(entryDisjointnessCmds, entryYieldPredicates));
                    }

                    if (proc.Ensures.Count > 0)
                    {
                        var exitDisjointnessCmds =
                            linearPermissionInstrumentation.ProcDisjointnessAssumeCmds(proc, false);
                        var exitYieldPredicates = proc.Ensures.Select(ensures =>
                                                                      ensures.Free
                ? (PredicateCmd) new AssumeCmd(ensures.tok, ensures.Condition)
                : (PredicateCmd) new AssertCmd(ensures.tok, ensures.Condition)).ToList();
                        yieldInfos.Add(new YieldInfo(exitDisjointnessCmds, exitYieldPredicates));
                    }
                }
            }
            else
            {
                Debug.Assert(false);
            }

            var filteredYieldInfos = yieldInfos.Where(info =>
                                                      info.invariantCmds.Any(predCmd => new GlobalAccessChecker().AccessesGlobal(predCmd.Expr)));

            if (filteredYieldInfos.Count() == 0)
            {
                return(new List <Declaration>());
            }

            Substitution assumeSubst = Substituter.SubstitutionFromDictionary(assumeMap);
            Substitution oldSubst    = Substituter.SubstitutionFromDictionary(oldLocalMap);
            Substitution subst       = Substituter.SubstitutionFromDictionary(map);
            List <Block> noninterferenceCheckerBlocks = new List <Block>();
            List <Block> labelTargets = new List <Block>();
            Block        noninterferenceCheckerBlock = BlockHelper.Block("exit", new List <Cmd>());

            labelTargets.Add(noninterferenceCheckerBlock);
            noninterferenceCheckerBlocks.Add(noninterferenceCheckerBlock);
            int yieldCount = 0;

            foreach (var kv in filteredYieldInfos)
            {
                var newCmds = new List <Cmd>(kv.disjointnessCmds);
                foreach (var predCmd in kv.invariantCmds)
                {
                    var newExpr = Substituter.ApplyReplacingOldExprs(assumeSubst, oldSubst, predCmd.Expr);
                    newCmds.Add(new AssumeCmd(predCmd.tok, newExpr));
                }

                foreach (var predCmd in kv.invariantCmds)
                {
                    if (predCmd is AssertCmd)
                    {
                        var       newExpr   = Substituter.ApplyReplacingOldExprs(subst, oldSubst, predCmd.Expr);
                        AssertCmd assertCmd = new AssertCmd(predCmd.tok, newExpr, predCmd.Attributes);
                        assertCmd.ErrorData = "Non-interference check failed";
                        newCmds.Add(assertCmd);
                    }
                }

                newCmds.Add(CmdHelper.AssumeCmd(Expr.False));
                noninterferenceCheckerBlock = BlockHelper.Block("L" + yieldCount++, newCmds);
                labelTargets.Add(noninterferenceCheckerBlock);
                noninterferenceCheckerBlocks.Add(noninterferenceCheckerBlock);
            }

            noninterferenceCheckerBlocks.Insert(0, BlockHelper.Block("enter", new List <Cmd>(), labelTargets));

            // Create the yield checker procedure
            noninterferenceCheckerName = civlTypeChecker.AddNamePrefix($"NoninterferenceChecker_{noninterferenceCheckerName}");
            var noninterferenceCheckerProc = DeclHelper.Procedure(noninterferenceCheckerName,
                                                                  inputs, new List <Variable>(), new List <Requires>(), new List <IdentifierExpr>(), new List <Ensures>());

            CivlUtil.AddInlineAttribute(noninterferenceCheckerProc);

            // Create the yield checker implementation
            var noninterferenceCheckerImpl = DeclHelper.Implementation(noninterferenceCheckerProc,
                                                                       inputs, new List <Variable>(), locals, noninterferenceCheckerBlocks);

            CivlUtil.AddInlineAttribute(noninterferenceCheckerImpl);
            return(new List <Declaration> {
                noninterferenceCheckerProc, noninterferenceCheckerImpl
            });
        }
Exemple #11
0
    private static void AddChecker(CivlTypeChecker civlTypeChecker, Action action, List<Declaration> decls)
    {
      var linearTypeChecker = civlTypeChecker.linearTypeChecker;
      // Note: The implementation should be used as the variables in the
      //       gate are bound to implementation and not to the procedure.
      Implementation impl = action.impl;
      List<Variable> inputs = impl.InParams;
      List<Variable> outputs = impl.OutParams;

      List<Variable> locals = new List<Variable>(2);
      var paLocal1 = civlTypeChecker.LocalVariable("pa1", civlTypeChecker.pendingAsyncType);
      var paLocal2 = civlTypeChecker.LocalVariable("pa2", civlTypeChecker.pendingAsyncType);
      var pa1 = Expr.Ident(paLocal1);
      var pa2 = Expr.Ident(paLocal2);
      
      if (civlTypeChecker.pendingAsyncType != null)
      {
        locals.Add(paLocal1);
        locals.Add(paLocal2);
      }

      List<Requires> requires = action.gate.Select(a => new Requires(false, a.Expr)).ToList();
      List<LinearityCheck> linearityChecks = new List<LinearityCheck>();

      foreach (var domain in linearTypeChecker.linearDomains.Values)
      {
        // Linear in vars
        var inVars = inputs.Union(action.modifiedGlobalVars)
          .Where(x => linearTypeChecker.FindDomainName(x) == domain.domainName)
          .Where(x => InKinds.Contains(linearTypeChecker.FindLinearKind(x)))
          .Select(Expr.Ident)
          .ToList();
        
        // Linear out vars
        var outVars = inputs.Union(outputs).Union(action.modifiedGlobalVars)
          .Where(x => linearTypeChecker.FindDomainName(x) == domain.domainName)
          .Where(x => OutKinds.Contains(linearTypeChecker.FindLinearKind(x)))
          .Select(Expr.Ident)
          .ToList();

        // First kind
        // Permissions in linear output variables are a subset of permissions in linear input variables.
        if (outVars.Count > 0)
        {
          linearityChecks.Add(new LinearityCheck(
            null,
            OutPermsSubsetInPerms(domain, inVars, outVars),
            $"Potential linearity violation in outputs for domain {domain.domainName}.",
            "variables"));
        }

        if (action is AtomicAction atomicAction && atomicAction.HasPendingAsyncs)
        {
          var PAs = Expr.Ident(atomicAction.impl.OutParams.Last());
          
          foreach (var pendingAsync in atomicAction.pendingAsyncs)
          {
            var pendingAsyncLinearParams = PendingAsyncLinearParams(linearTypeChecker, domain, pendingAsync, pa1);

            if (pendingAsyncLinearParams.Count == 0) continue;

            // Second kind
            // Permissions in linear output variables + linear inputs of a single pending async
            // are a subset of permissions in linear input variables.
            var exactlyOnePA = Expr.And(
              ExprHelper.FunctionCall(pendingAsync.pendingAsyncCtor.membership, pa1),
              Expr.Eq(Expr.Select(PAs, pa1), Expr.Literal(1)));
            var outSubsetInExpr = OutPermsSubsetInPerms(domain, inVars, pendingAsyncLinearParams.Union(outVars));
            linearityChecks.Add(new LinearityCheck(
              exactlyOnePA,
              outSubsetInExpr,
              $"Potential linearity violation in outputs and pending async of {pendingAsync.proc.Name} for domain {domain.domainName}.",
              $"single_{pendingAsync.proc.Name}"));

            // Third kind
            // If there are two identical pending asyncs, then their input permissions mut be empty.
            var twoIdenticalPAs = Expr.And(
              ExprHelper.FunctionCall(pendingAsync.pendingAsyncCtor.membership, pa1),
              Expr.Ge(Expr.Select(PAs, pa1), Expr.Literal(2)));
            var emptyPerms = OutPermsSubsetInPerms(domain, Enumerable.Empty<Expr>(), pendingAsyncLinearParams);
            linearityChecks.Add(new LinearityCheck(
              twoIdenticalPAs,
              emptyPerms,
              $"Potential linearity violation in identical pending asyncs of {pendingAsync.proc.Name} for domain {domain.domainName}.",
              $"identical_{pendingAsync.proc.Name}"));
          }

          var pendingAsyncs = atomicAction.pendingAsyncs.ToList();
          for (int i = 0; i < pendingAsyncs.Count; i++)
          {
            var pendingAsync1 = pendingAsyncs[i];
            for (int j = i; j < pendingAsyncs.Count; j++)
            {
              var pendingAsync2 = pendingAsyncs[j];

              var pendingAsyncLinearParams1 = PendingAsyncLinearParams(linearTypeChecker, domain, pendingAsync1, pa1);
              var pendingAsyncLinearParams2 = PendingAsyncLinearParams(linearTypeChecker, domain, pendingAsync2, pa2);
              
              if (pendingAsyncLinearParams1.Count == 0 || pendingAsyncLinearParams2.Count == 0) continue;

              // Fourth kind
              // Input permissions of two non-identical pending asyncs (possibly of the same action)
              // are a subset of permissions in linear input variables.
              var membership = Expr.And(
                Expr.Neq(pa1, pa2),
                Expr.And(
                  ExprHelper.FunctionCall(pendingAsync1.pendingAsyncCtor.membership, pa1),
                  ExprHelper.FunctionCall(pendingAsync2.pendingAsyncCtor.membership, pa2)));

              var existing = Expr.And(
                Expr.Ge(Expr.Select(PAs, pa1), Expr.Literal(1)),
                Expr.Ge(Expr.Select(PAs, pa2), Expr.Literal(1)));

              var noDuplication = OutPermsSubsetInPerms(domain, inVars, pendingAsyncLinearParams1.Union(pendingAsyncLinearParams2));

              linearityChecks.Add(new LinearityCheck(
                Expr.And(membership, existing),
                noDuplication,
                $"Potential lnearity violation in pending asyncs of {pendingAsync1.proc.Name} and {pendingAsync2.proc.Name} for domain {domain.domainName}.",
                $"distinct_{pendingAsync1.proc.Name}_{pendingAsync2.proc.Name}"));
            }
          }
        }
      }

      if (linearityChecks.Count == 0) return;

      // Create checker blocks
      List<Block> checkerBlocks = new List<Block>(linearityChecks.Count);
      foreach (var lc in linearityChecks)
      {
        List<Cmd> cmds = new List<Cmd>(2);
        if (lc.assume != null)
        {
          cmds.Add(CmdHelper.AssumeCmd(lc.assume));
        }
        cmds.Add(new AssertCmd(action.proc.tok, lc.assert) { ErrorData = lc.message });
        var block = new Block(Token.NoToken, lc.name, cmds, CmdHelper.ReturnCmd);
        CivlUtil.ResolveAndTypecheck(block, ResolutionContext.State.Two);
        checkerBlocks.Add(block);
      }
      
      // Create init blocks
      List<Block> blocks = new List<Block>(linearityChecks.Count + 1);
      blocks.Add(
        new Block(
          Token.NoToken,
          "init",
          new List<Cmd> { CmdHelper.CallCmd(action.proc, inputs, outputs) },
          new GotoCmd(Token.NoToken, checkerBlocks)));
      blocks.AddRange(checkerBlocks);

      // Create the whole check procedure
      string checkerName = civlTypeChecker.AddNamePrefix($"LinearityChecker_{action.proc.Name}");
      Procedure linCheckerProc = new Procedure(Token.NoToken, checkerName, new List<TypeVariable>(),
        inputs, outputs, requires, action.proc.Modifies, new List<Ensures>());
      Implementation linCheckImpl = new Implementation(Token.NoToken, checkerName,
        new List<TypeVariable>(), inputs, outputs, locals, blocks);
      linCheckImpl.Proc = linCheckerProc;
      decls.Add(linCheckImpl);
      decls.Add(linCheckerProc);
    }