This function automatically computes and inserts leakage-related loop invariants.
 The invariants are of the form:
 leakage = leakage_before_entering + loop_counter * (loop_body_cost + control_block_cost)
332918
def summarize_loops! decl

      cfg = cfg_construction


      # Identify loop-cost related annotations
      loop_vars = []
      if (has_annotation?(decl, INV_VAR_ANNOTATION_NAME)) then
        decl.body.select{ |s| is_annotation_stmt?(s, INV_VAR_ANNOTATION_NAME)}.each do |s|
          value = get_annotation_value s
          loop_vars.push(value)
        end
      end

      loop_identification.loops.each do |head, blocks|

        # Only deal with loops that are in the procedure we are processing.
        loop_is_in_decl = decl.body.blocks.find do |b|
          b.name == head.name && decl.name == head.parent.parent.name
        end

        next unless loop_is_in_decl

        # Create leakage_before_entering variable and insert right before the loop head.
        lkg_before_var = decl.body.fresh_var("$loop_l","i32")
        lkg_before_asn = AssignStatement.new lhs: lkg_before_var, rhs: bpl("$l")

        entry = cfg.predecessors[head].detect{ |b| !blocks.include?(b) }
        entry.statements.last.insert_before(lkg_before_asn)


        # Identify control blocks, body blocks and compute their costs.
        control_blocks, exit_block = extract_control_blocks(head, blocks, cfg)
        body_blocks = blocks - control_blocks

        # Identify non-nested branches, their consequent blocks and their alternative blocks.
        # TODO: raise error/warning when we encounetr a non-nested branch.

        gotos = extract_branches body_blocks

        branches = {}
        gotos.each do |goto|
          consequent = goto.identifiers.first.declaration
          alternative = goto.identifiers.last.declaration
          branches[goto] = consequent, alternative
        end

        straight_line_blocks = body_blocks
        branches.each_value do |cons, alt|
          straight_line_blocks -= [cons, alt]
        end

        control_cost = control_blocks.inject(0) { |acc, blk| (acc + (cost_of blk)) }
        straight_line_cost = straight_line_blocks.inject(0) { |acc, blk| (acc + (cost_of blk)) }

        # Identify the loop_counter variable as the intersection of live variables of the head
        # block and its predecessor.
        counter_update_block = cfg.predecessors[head].detect{ |b| blocks.include?(b) }
        args = decl.declarations.inject([]) { |acc, d| acc << d.idents[0].name }
        counter = ((liveness.live[head] & liveness.live[counter_update_block]) - args).first

        cons_inv = ""
        branches.values.each_with_index do |(cons, alt), idx|
          cons_cost = cost_of cons
          #alt_cost = cost_of alt
          cons_inv += "$sdiv.i32(#{loop_vars[idx]}+ #{counter} - 1,64)*#{cons_cost}"
          #puts "(#{continuation} - (old+ #{counter} - 1)/64)*#{alt_cost}"
        end

        straight_line_inv = "(#{counter}#{' - 1' unless cons_inv.empty?})*(#{straight_line_cost}+#{control_cost})";

        #puts "assert ($l == #{lkg_before_var}+#{straight_line_inv}#{' + ' unless cons_inv.empty?}#{cons_inv});"
        # Compute and insert leakage invariant at the beginning of the head block.
        head.prepend_children(:statements,
          bpl("assert ($l == #{lkg_before_var}+#{straight_line_inv}#{' + ' unless cons_inv.empty?}#{cons_inv});"))

      end

    end
342578
def invariant(arg1, arg2=None):
    

    desc = ""
    predicate = lambda x: x

    if isinstance(arg1, str):
        desc = arg1
        predicate = arg2
    else:
        desc = get_function_source(arg1)
        predicate = arg1

    def invariant(c):
        def check(name, func):
            exceptions = ("__getitem__", "__setitem__", "__lt__", "__le__", "__eq__",
                          "__ne__", "__gt__", "__ge__", "__init__")

            if name.startswith("__") and name.endswith("__") and name not in exceptions:
                return False

            if not ismethod(func) and not isfunction(func):
                return False

            if getattr(func, "__self__", None) is c:
                return False

            return True

        class InvariantContractor(c):
            pass

        for name, value in [(name, getattr(c, name)) for name in dir(c)]:
            if check(name, value):
                setattr(InvariantContractor, name,
                        condition(desc, predicate, name != "__init__", True, True)(value))
        return InvariantContractor
    return invariant
782137
def _check_errors(self):
        """"""
        # use this to make sure that sweep, sstart, sstop, and sinterval
        # all have values if one of them has values
        # (P^Q^R^S) OR (-P and -Q and -R and -S)
        # above is the minimal form for this logical statement in DNF
        if not ((self._inn(self.args.sweep) and self._inn(self.args.sstart)
                 and self._inn(self.args.sstop) and self._inn(self.args.sinterval))
                or
                (not self._inn(self.args.sweep) and not self._inn(self.args.sstart) and not
                 self._inn(self.args.sstop) and not self._inn(self.args.sinterval))):
            mutually_inclusive = ["sweep", "sstart", "sstop", "sinterval"]
            print_str = ""
            for each in mutually_inclusive:
                print_str += "    {0}: {1}\n".format(each, getattr(self.args, each))
            raise AssertionError("""You specified one or more of the --sweep,
            --sstart, --stop, or --sinterval arguments but did not specify all of
            them. All of them are required when running the program in sweep mode.
            Do not specify any of these arguments if not running the program in
            sweep mode.\n{0}""".format(print_str))
1312896
def add_invariant_checks(cls: type) -> None:
    """"""
    # Candidates for the decoration as list of (name, dir() value)
    init_name_func = None  # type: Optional[Tuple[str, Callable[..., None]]]
    names_funcs = []  # type: List[Tuple[str, Callable[..., None]]]
    names_properties = []  # type: List[Tuple[str, property]]

    # Filter out entries in the directory which are certainly not candidates for decoration.
    for name, value in [(name, getattr(cls, name)) for name in dir(cls)]:
        # We need to ignore __repr__ to prevent endless loops when generating error messages.
        # __getattribute__, __setattr__ and __delattr__ are too invasive and alter the state of the instance.
        # Hence we don't consider them "public".
        if name in ["__repr__", "__getattribute__", "__setattr__", "__delattr__"]:
            continue

        if name == "__init__":
            assert inspect.isfunction(value) or isinstance(value, _SLOT_WRAPPER_TYPE), \
                "Expected __init__ to be either a function or a slot wrapper, but got: {}".format(type(value))

            init_name_func = (name, value)
            continue

        if not inspect.isfunction(value) and not isinstance(value, _SLOT_WRAPPER_TYPE) and \
                not isinstance(value, property):
            continue

        # Ignore class methods
        if getattr(value, "__self__", None) is cls:
            continue

        # Ignore "protected"/"private" methods
        if name.startswith("_") and not (name.startswith("__") and name.endswith("__")):
            continue

        if inspect.isfunction(value) or isinstance(value, _SLOT_WRAPPER_TYPE):
            names_funcs.append((name, value))

        elif isinstance(value, property):
            names_properties.append((name, value))

        else:
            raise NotImplementedError("Unhandled directory entry of class {} for {}: {}".format(cls, name, value))

    if init_name_func:
        name, func = init_name_func
        wrapper = _decorate_with_invariants(func=func, is_init=True)
        setattr(cls, name, wrapper)

    for name, func in names_funcs:
        wrapper = _decorate_with_invariants(func=func, is_init=False)
        setattr(cls, name, wrapper)

    for name, prop in names_properties:
        new_prop = property(  # type: ignore
            fget=_decorate_with_invariants(func=prop.fget, is_init=False) if prop.fget else None,
            fset=_decorate_with_invariants(func=prop.fset, is_init=False) if prop.fset else None,
            fdel=_decorate_with_invariants(func=prop.fdel, is_init=False) if prop.fdel else None,
            doc=prop.__doc__)
        setattr(cls, name, new_prop)
1134930
function deterministicGenerateK(curve, hash, d, checkSig, nonce) {
    enforceType("Buffer", hash);
    enforceType(BigInteger, d);

    if (nonce) {
        hash = sha256(Buffer.concat([hash, Buffer.alloc(nonce)]));
    }

    // sanity check
    assert.equal(hash.length, 32, "Hash must be 256 bit");

    var x = d.toBuffer(32);
    var k = Buffer.alloc(32);
    var v = Buffer.alloc(32);

    // Step B
    v.fill(1);

    // Step C
    k.fill(0);

    // Step D
    k = HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k);

    // Step E
    v = HmacSHA256(v, k);

    // Step F
    k = HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k);

    // Step G
    v = HmacSHA256(v, k);

    // Step H1/H2a, ignored as tlen === qlen (256 bit)
    // Step H2b
    v = HmacSHA256(v, k);

    var T = BigInteger.fromBuffer(v);

    // Step H3, repeat until T is within the interval [1, n - 1]
    while (T.signum() <= 0 || T.compareTo(curve.n) >= 0 || !checkSig(T)) {
        k = HmacSHA256(Buffer.concat([v, new Buffer([0])]), k);
        v = HmacSHA256(v, k);

        // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
        // Step H2b again
        v = HmacSHA256(v, k);

        T = BigInteger.fromBuffer(v);
    }

    return T;
}
866653
def calculate_dot_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=2, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    if operator.inputs[0].type.shape != operator.inputs[1].type.shape:
        raise RuntimeError('Input shapes must be identical')

    # Assume that inputs are [N, C]- or [N, C, 1, 1]-tensors
    output_shape = copy.deepcopy(operator.inputs[0].type.shape)
    output_shape[1] = 1
    operator.outputs[0].type.shape = output_shape
918966
def _check_structure(self):
        '''
        
        '''
        # Collect all variable names and operator names
        unused_variables = set()
        unused_operators = set()
        for variable in self.unordered_variable_iterator():
            unused_variables.add(variable.full_name)
        for operator in self.unordered_operator_iterator():
            unused_operators.add(operator.full_name)

        for operator in self.unordered_operator_iterator():
            for variable in operator.inputs:
                # A variable is used by an operator, so we remove the variable from the unused-variable list.
                unused_variables.discard(variable.full_name)
                # A operator has an input, so we remove the operator from the unused-operator list.
                unused_operators.discard(operator.full_name)
            for variable in operator.outputs:
                # A variable is used by an operator, so we remove the variable from the unused-variable list.
                unused_variables.discard(variable.full_name)
                # A operator has an output, so we remove the operator from the unused-operator list.
                unused_operators.discard(operator.full_name)

        if len(unused_variables) > 0:
            raise RuntimeError('Isolated variables exist: %s' % unused_variables)

        if len(unused_operators) > 0:
            raise RuntimeError('Isolated operators exist: %s' % unused_operators)
1118193
private static boolean checkForStateChangeHelper(
      Node n, boolean checkForNewObjects, AbstractCompiler compiler) {
    // Rather than id which ops may have side effects, id the ones
    // that we know to be safe
    switch (n.getToken()) {
      case THROW:
        // Throw is a side-effect by definition.
      case YIELD:
      case AWAIT:
      case FOR_AWAIT_OF:
        // Context switches can conceal side-effects.
      case FOR_OF:
      case FOR_IN:
        // Enhanced for loops are almost always side-effectful; it's not worth checking them
        // further. Particularly, they represent a kind of assignment op.
      case VAR:
      case LET:
      case CONST:
      case EXPORT:
        // Variable declarations are side-effects.
        return true;

      case OBJECTLIT:
      case ARRAYLIT:
      case REGEXP:
        if (checkForNewObjects) {
          return true;
        }
        break;

      case REST:
      case SPREAD:
        if (iteratesImpureIterable(n)) {
          return true;
        }
        break;

      case NAME:
        // TODO(b/129564961): Consider EXPORT declarations.
        if (n.hasChildren()) {
          // This is the left side of a var/let/const
          return true;
        }
        break;

      case FUNCTION:
        // Function expressions don't have side-effects, but function
        // declarations change the namespace. Either way, we don't need to
        // check the children, since they aren't executed at declaration time.
        return checkForNewObjects || isFunctionDeclaration(n);

      case GETTER_DEF:
      case SETTER_DEF:
      case MEMBER_FUNCTION_DEF:
        // simply defining a member function, getter, or setter has no side effects
        return false;

      case CLASS:
        return checkForNewObjects || isClassDeclaration(n)
            // Check the extends clause for side effects.
            || checkForStateChangeHelper(n.getSecondChild(), checkForNewObjects, compiler)
            // Check for class members that are computed properties with side effects.
            || checkForStateChangeHelper(n.getLastChild(), checkForNewObjects, compiler);

      case CLASS_MEMBERS:
        for (Node member = n.getFirstChild(); member != null; member = member.getNext()) {
          if (member.isComputedProp()
              && checkForStateChangeHelper(member.getFirstChild(), checkForNewObjects, compiler)) {
            return true;
          }
        }
        return false;

      case NEW:
        if (checkForNewObjects) {
          return true;
        }

        if (!constructorCallHasSideEffects(n)) {
          // loop below will see if the constructor parameters have
          // side-effects
          break;
        }
        return true;

      case CALL:
        // calls to functions that have no side effects have the no
        // side effect property set.
        if (!functionCallHasSideEffects(n, compiler)) {
          // loop below will see if the function parameters have
          // side-effects
          break;
        }
        return true;

      case TAGGED_TEMPLATELIT:
        // TODO(b/128527671): Inspect the children of the expression for side-effects.
        return functionCallHasSideEffects(n, compiler);

      case CAST:
      case AND:
      case BLOCK:
      case ROOT:
      case EXPR_RESULT:
      case HOOK:
      case IF:
      case PARAM_LIST:
      case NUMBER:
      case OR:
      case THIS:
      case TRUE:
      case FALSE:
      case NULL:
      case STRING:
      case STRING_KEY:
      case SWITCH:
      case TEMPLATELIT_SUB:
      case TRY:
      case EMPTY:
      case TEMPLATELIT:
      case TEMPLATELIT_STRING:
      case COMPUTED_PROP:
        break;

      default:
        if (isSimpleOperator(n)) {
          break;
        }

        if (isAssignmentOp(n)) {
          Node assignTarget = n.getFirstChild();
          if (assignTarget.isName()) {
            return true;
          }

          // Assignments will have side effects if
          // a) The RHS has side effects, or
          // b) The LHS has side effects, or
          // c) A name on the LHS will exist beyond the life of this statement.
          if (checkForStateChangeHelper(n.getFirstChild(), checkForNewObjects, compiler)
              || checkForStateChangeHelper(n.getLastChild(), checkForNewObjects, compiler)) {
            return true;
          }

          if (isGet(assignTarget)) {
            // If the object being assigned to is a local object, don't
            // consider this a side-effect as it can't be referenced
            // elsewhere.  Don't do this recursively as the property might
            // be an alias of another object, unlike a literal below.
            Node current = assignTarget.getFirstChild();
            if (evaluatesToLocalValue(current)) {
              return false;
            }

            // A literal value as defined by "isLiteralValue" is guaranteed
            // not to be an alias, or any components which are aliases of
            // other objects.
            // If the root object is a literal don't consider this a
            // side-effect.
            while (isGet(current)) {
              current = current.getFirstChild();
            }

            return !isLiteralValue(current, true);
          } else {
            // TODO(johnlenz): remove this code and make this an exception. This
            // is here only for legacy reasons, the AST is not valid but
            // preserve existing behavior.
            return !isLiteralValue(assignTarget, true);
          }
        }

        return true;
    }

    for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
      if (checkForStateChangeHelper(c, checkForNewObjects, compiler)) {
        return true;
      }
    }

    return false;
  }
31025
def code_constants(self):
        
        # TODO: remove link register values
        return [const.value for block in self.blocks for const in block.vex.constants]
247467
function tighten(statements) {
                var cur, prev;
                for (var i = 0, ret1 = []; i < statements.length; ++i) {
                        cur = statements[i];
                        if (cur[0] == "block") {
                                if (cur[1]) {
                                        ret1.push.apply(ret1, cur[1]);
                                }
                        } else {
                                ret1.push(cur);
                        }
                }
                prev = null;
                for (var i = 0, ret2 = []; i < ret1.length; ++i) {
                        cur = ret1[i];
                        if (prev && ((cur[0] == "var" && prev[0] == "var") ||
                                     (cur[0] == "const" && prev[0] == "const"))) {
                                prev[1] = prev[1].concat(cur[1]);
                        } else {
                                ret2.push(cur);
                                prev = cur;
                        }
                }
                if (!options.make_seqs)
                        return ret2;
                prev = null;
                for (var i = 0, ret3 = []; i < ret2.length; ++i) {
                        cur = ret2[i];
                        if (!prev) {
                                if (cur[0] == "stat") {
                                        prev = [ "seq", cur[1] ];
                                        ret3.push([ "stat", prev ]);
                                } else {
                                        ret3.push(cur);
                                }
                        } else if (cur[0] == "stat") {
                                prev.push(cur[1]);
                        } else if (cur[0] == "seq") {
                                prev.push.apply(prev, slice(cur, 1));
                        } else {
                                prev = null;
                                ret3.push(cur);
                        }
                }
                return ret3.map(walk);
        }
939315
def _stmt_inside_loop(self, stmt_idx):
        

        # TODO: This is slow. Fix the performance issue

        for node in self.loop.body_nodes:
            if node.addr.stmt_idx <= stmt_idx < node.addr.stmt_idx + node.size:
                return True
        return False
1294857
def check(self, cfg, state, peek_blocks):
        

        # Get the current CFGNode
        node = self._get_cfg_node(cfg, state)

        if node is None:
            l.error("Failed to find CFGNode for state %s on the control flow graph.", state)
            return False

        # crawl the graph to see if we can reach the target function within the limited steps
        for src, dst in self._dfs_edges(cfg.graph, node, max_steps=peek_blocks):
            the_node = None
            if src.addr == self.function.addr:
                the_node = src
            elif dst.addr == self.function.addr:
                the_node = dst

            if the_node is not None:
                if self.arguments is None:
                    # we do not care about arguments
                    return True

                else:
                    # check arguments
                    arch = state.arch
                    state = the_node.input_state
                    same_arguments = self._check_arguments(arch, state)

                    if same_arguments:
                        # all arguments are the same!
                        return True

        l.debug("SimState %s will not reach function %s.", state, self.function)
        return False
1166105
def bitwise_and(self, t):
        
        """
        The following code implements the and operations as presented in the paper
        'Signedness-Agnostic Program Analysis: Precise Integer Bounds for Low-Level Code'
        """
        s = self

        def number_of_ones(n):
            ctr = 0
            while n > 0:
                ctr += 1
                n &= n - 1
            return ctr

        # Optimization: if one of the two intervals is an integer and contains only one one we can be precise
        for a, b in [[s, t], [t, s]]:
            if a.is_integer and number_of_ones(a.lower_bound) == 1:
                if a.lower_bound == (1 << (t.bits - 1)):
                    # It's testing the sign bit
                    stride = 1 << (a.bits - 1)
                    if b.is_integer:
                        if b.lower_bound == stride:
                            return StridedInterval(bits=b.bits, stride=0, lower_bound=stride, upper_bound=stride)
                        else:
                            return StridedInterval(bits=b.bits, stride=0, lower_bound=0, upper_bound=0)
                    else:
                        is_sol = (a.lower_bound - b.lower_bound) % b.stride == 0 and b.lower_bound <= a.lower_bound <= b.upper_bound
                        if is_sol:
                            return StridedInterval(bits=b.bits, stride=stride, lower_bound=0, upper_bound=stride)
                        else:
                            return StridedInterval(bits=b.bits, stride=0, lower_bound=0, upper_bound=0)
                else:
                    #FIXME: implement case only one 1 not in first position
                    pass

        # paper's and
        new_interval = s.bitwise_not().bitwise_or(t.bitwise_not()).bitwise_not()
        return new_interval.normalize()
1137815
def calculate_padding_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    output_shape = copy.deepcopy(operator.inputs[0].type.shape)

    params = operator.raw_operator.padding
    if len(params.paddingAmounts.borderAmounts) > 0:
        output_shape[2] += params.paddingAmounts.borderAmounts[0].startEdgeSize
        output_shape[2] += params.paddingAmounts.borderAmounts[0].endEdgeSize
        output_shape[3] += params.paddingAmounts.borderAmounts[1].startEdgeSize
        output_shape[3] += params.paddingAmounts.borderAmounts[1].endEdgeSize

    operator.outputs[0].type.shape = output_shape
868586
public int getInstanceSlot(Instruction ins, ConstantPoolGen cpg) throws DataflowAnalysisException {
        if (!isValid()) {
            throw new DataflowAnalysisException("Accessing invalid frame at " + ins);
        }
        int numConsumed = ins.consumeStack(cpg);
        if (numConsumed == Const.UNPREDICTABLE) {
            throw new DataflowAnalysisException("Unpredictable stack consumption in " + ins);
        }
        if (numConsumed > getStackDepth()) {
            throw new DataflowAnalysisException("Stack underflow " + ins);
        }
        return getNumSlots() - numConsumed;
    }
1185168
def std_check_in(dataset, name, allowed_vals):
    
    if not hasattr(dataset, name):
        return 0

    ret_val = 1
    if getattr(dataset, name) in allowed_vals:
        ret_val += 1

    return ret_val
404466
def inits_t(wrap):
    
    return Transformation(
        'inits',
        lambda sequence: [wrap(sequence[:i]) for i in reversed(range(len(sequence) + 1))],
        {ExecutionStrategies.PRE_COMPUTE}
    )