def _legalize(module, dmm, fndesc):
    """
    Legalize the code in the module.
    Returns True if the module is legal for the rewrite pass that removes
    unnecessary refcounts.
    """

    def valid_output(ty):
        """
        Valid output are any type that does not need refcount
        """
        model = dmm[ty]
        return not model.contains_nrt_meminfo()

    def valid_input(ty):
        """
        Valid input are any type that does not need refcount except Array.
        """
        return valid_output(ty) or isinstance(ty, types.Array)


    # Ensure no reference to function marked as
    # "numba_args_may_always_need_nrt"
    try:
        nmd = module.get_named_metadata("numba_args_may_always_need_nrt")
    except KeyError:
        # Nothing marked
        pass
    else:
        # Has functions marked as "numba_args_may_always_need_nrt"
        if len(nmd.operands) > 0:
            # The pass is illegal for this compilation unit.
            return False

    # More legalization base on function type
    argtypes = fndesc.argtypes
    restype = fndesc.restype
    calltypes = fndesc.calltypes

    # Legalize function arguments
    for argty in argtypes:
        if not valid_input(argty):
            return False

    # Legalize function return
    if not valid_output(restype):
        return False

    # Legalize all called functions
    for callty in calltypes.values():
        if callty is not None and not valid_output(callty.return_type):
            return False

    # Ensure no allocation
    for fn in module.functions:
        if fn.name.startswith("NRT_"):
            if fn.name not in _accepted_nrtfns:
                return False

    return True

    Legalize the code in the module.
    Returns True if the module is legal for the rewrite pass that removes
    unnecessary refcounts.
    
numba/core/removerefctpass.py