Skip to content

Commit

Permalink
Merge pull request #386 from phanrahan/default-nodebug
Browse files Browse the repository at this point in the history
Make debug mode optional
  • Loading branch information
leonardt committed Apr 30, 2019
2 parents f4ae6ca + 01b191b commit c3030d5
Show file tree
Hide file tree
Showing 21 changed files with 216 additions and 150 deletions.
4 changes: 2 additions & 2 deletions magma/backend/coreir_.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def compile_definition_to_module_definition(self, definition, module_definition)
wiredefaultclock(definition, instance)
wireclock(definition, instance)
coreir_instance = self.compile_instance(instance, module_definition)
if get_codegen_debug_info() and instance.debug_info:
if get_codegen_debug_info() and getattr(instance, "debug_info", False):
coreir_instance.add_metadata("filename", json.dumps(make_relative(instance.debug_info.filename)))
coreir_instance.add_metadata("lineno", json.dumps(str(instance.debug_info.lineno)))
for name, port in instance.interface.ports.items():
Expand Down Expand Up @@ -364,7 +364,7 @@ def is_clock_or_nested_clock(p):
source = module_definition.select(non_input_ports[value])
sink = module_definition.select(magma_port_to_coreir(port))
module_definition.connect(source, sink)
if get_codegen_debug_info() and hasattr(port, "debug_info"):
if get_codegen_debug_info() and getattr(port, "debug_info", False):
module_definition.add_metadata(source, sink, "filename", json.dumps(make_relative(port.debug_info.filename)))
module_definition.add_metadata(source, sink, "lineno", json.dumps(str(port.debug_info.lineno)))

Expand Down
10 changes: 6 additions & 4 deletions magma/backend/verilog.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def arg(k,v):
args = []
debug_str = ""
for k, v in self.interface.ports.items():
if hasattr(v, "debug_info") and get_codegen_debug_info():
if getattr(v, "debug_info", False) and get_codegen_debug_info():
filename, lineno, module = v.debug_info
#print('arg', k, v,)
if v.isinput():
Expand All @@ -131,7 +131,7 @@ def arg(k,v):
args.append( vname(v) )
else:
args.append( arg(k,vname(v)) )
if hasattr(v, "debug_info") and get_codegen_debug_info():
if getattr(v, "debug_info", False) and get_codegen_debug_info():
debug_str += f"// Argument {k}({vname(v)}) wired at {make_relative(filename)}:{lineno}\n"

params = []
Expand Down Expand Up @@ -199,7 +199,9 @@ def wire(port):
# emit the structured verilog for each instance
for instance in cls.instances:
wiredefaultclock(cls, instance)
if instance.debug_info.filename and instance.debug_info.lineno and get_codegen_debug_info():
if getattr(instance, "debug_info", False) and \
instance.debug_info.filename and instance.debug_info.lineno and \
get_codegen_debug_info():
s += f"// Instanced at {make_relative(instance.debug_info.filename)}:{instance.debug_info.lineno}\n"
s += compileinstance(instance) + ";\n"

Expand All @@ -220,7 +222,7 @@ def wire(port):
else:
iname = vname(port)
oname = vname(output)
if hasattr(port, "debug_info") and get_codegen_debug_info():
if getattr(port, "debug_info", False) and get_codegen_debug_info():
s += f"// Wired at {make_relative(port.debug_info[0])}:{port.debug_info[1]}\n"
s += 'assign %s = %s;\n' % (iname, oname)
else:
Expand Down
38 changes: 27 additions & 11 deletions magma/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .array import ArrayType
from .tuple import TupleType
from .bit import VCC, GND
from .config import get_debug_mode
from .debug import get_callee_frame_info, debug_info
from .logging import warning
from .port import report_wiring_warning
Expand Down Expand Up @@ -73,11 +74,15 @@ def __new__(metacls, name, bases, dct):

if 'coreir_lib' not in dct:
dct['coreir_lib'] = "global"
if "debug_info" not in dct:
callee_frame = inspect.getframeinfo(inspect.currentframe().f_back.f_back)
module = inspect.getmodule(inspect.stack()[2][0])
dct["debug_info"] = debug_info(callee_frame.filename,
callee_frame.lineno, module)
if get_debug_mode():
if not dct.get("debug_info", False):
callee_frame = inspect.getframeinfo(inspect.currentframe().f_back.f_back)
module = inspect.getmodule(inspect.stack()[2][0])
dct["debug_info"] = debug_info(callee_frame.filename,
callee_frame.lineno, module)
else:
dct["debug_info"] = None


# create a new circuit class
cls = type.__new__(metacls, name, bases, dct)
Expand All @@ -95,9 +100,10 @@ def __new__(metacls, name, bases, dct):

def __call__(cls, *largs, **kwargs):
#print('CircuitKind call:', largs, kwargs)
debug_info = get_callee_frame_info()
self = super(CircuitKind, cls).__call__(*largs, **kwargs)
self.set_debug_info(debug_info)
if get_debug_mode():
debug_info = get_callee_frame_info()
self.set_debug_info(debug_info)

# instance interface for this instance
if hasattr(cls, 'IO'):
Expand Down Expand Up @@ -262,7 +268,10 @@ def debug_name(self):
return f"{defn_str}.{self.name}"

def __call__(input, *outputs, **kw):
debug_info = get_callee_frame_info()
if get_debug_mode():
debug_info = get_callee_frame_info()
else:
debug_info = None

no = len(outputs)
if len(outputs) == 1:
Expand Down Expand Up @@ -364,7 +373,10 @@ def __repr__(self):

# DeclareCircuit Factory
def DeclareCircuit(name, *decl, **args):
debug_info = get_callee_frame_info()
if get_debug_mode():
debug_info = get_callee_frame_info()
else:
debug_info = None
dct = dict(
IO=decl,
debug_info=debug_info,
Expand Down Expand Up @@ -475,7 +487,8 @@ def place(cls, inst):
inst.name = f"{type(inst).name}_inst{str(cls.instanced_circuits_counter[type(inst).name])}"
cls.instanced_circuits_counter[type(inst).name] += 1
inst.defn = cls
inst.stack = inspect.stack()
if get_debug_mode():
inst.stack = inspect.stack()
cls.instances.append(inst)


Expand All @@ -499,7 +512,10 @@ class Circuit(CircuitType):

# DefineCircuit Factory
def DefineCircuit(name, *decl, **args):
debug_info = get_callee_frame_info()
if get_debug_mode():
debug_info = get_callee_frame_info()
else:
debug_info = None
global currentDefinition
if currentDefinition:
currentDefinitionStack.append(currentDefinition)
Expand Down
2 changes: 1 addition & 1 deletion magma/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def __init__(self, main):
self.has_mantle_circuit = False

def __call__(self, definition):
if definition.debug_info.module is not None and \
if getattr(definition, "debug_info", False) and \
definition.debug_info.module.__name__.split(".")[0] == "mantle":
self.has_mantle_circuit = True

Expand Down
13 changes: 13 additions & 0 deletions magma/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,16 @@ def set_compile_dir(target):

def get_compile_dir():
return __COMPILE_DIR


__DEBUG_MODE = False


def set_debug_mode(value=True):
global __DEBUG_MODE
assert value in {True, False}
__DEBUG_MODE = value


def get_debug_mode():
return __DEBUG_MODE
3 changes: 2 additions & 1 deletion magma/debug.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import inspect
import collections
import magma
from magma.config import get_debug_mode


debug_info = collections.namedtuple("debug_info", ["filename", "lineno", "module"])
Expand Down Expand Up @@ -28,7 +29,7 @@ def debug_wire(fn):
# TODO: We could check that fn has the correct interface
# wire(i, o, debug_info)
def wire(i, o, debug_info=None):
if debug_info is None:
if get_debug_mode() and debug_info is None:
debug_info = get_callee_frame_info()
return fn(i, o, debug_info)
return wire
Expand Down
28 changes: 17 additions & 11 deletions magma/port.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,27 @@


def report_wiring_error(message, debug_info):
error(f"\033[1m{make_relative(debug_info[0])}:{debug_info[1]}: {message}",
include_wire_traceback=True)
try:
error(get_source_line(debug_info[0], debug_info[1]))
except FileNotFoundError:
error(f" Could not find file {debug_info[0]}")
if debug_info:
error(f"\033[1m{make_relative(debug_info[0])}:{debug_info[1]}: {message}",
include_wire_traceback=True)
try:
error(get_source_line(debug_info[0], debug_info[1]))
except FileNotFoundError:
error(f" Could not find file {debug_info[0]}")
else:
error(message)


def report_wiring_warning(message, debug_info):
# TODO: Include wire traceback support
warning(f"\033[1m{make_relative(debug_info[0])}:{debug_info[1]}: {message}")
try:
warning(get_source_line(debug_info[0], debug_info[1]))
except FileNotFoundError:
warning(f" Could not find file {debug_info[0]}")
if debug_info:
warning(f"\033[1m{make_relative(debug_info[0])}:{debug_info[1]}: {message}")
try:
warning(get_source_line(debug_info[0], debug_info[1]))
except FileNotFoundError:
warning(f" Could not find file {debug_info[0]}")
else:
warning(message)


def flip(direction):
Expand Down
1 change: 0 additions & 1 deletion magma/ssa/ssa.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import ast
import types
from collections import defaultdict
import inspect
import astor


Expand Down
68 changes: 46 additions & 22 deletions magma/syntax/combinational.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import types
from magma.debug import debug_info
from magma.ssa import convert_tree_to_ssa
from magma.config import get_debug_mode


class CircuitDefinitionSyntaxError(Exception):
Expand All @@ -31,7 +32,10 @@ class IfTransformer(ast.NodeTransformer):
def __init__(self, filename, lines):
super().__init__()
self.filename = filename
self.lines, self.starting_line = lines
if lines:
self.lines, self.starting_line = lines
else:
self.lines, self.starting_line = None, None

def flatten(self, _list):
"""1-deep flatten"""
Expand Down Expand Up @@ -60,35 +64,50 @@ def visit_If(self, node):
raise NotImplementedError("Assigning more than one value")
key = ast.dump(stmt.targets[0])
if key in seen:
# TODO: Print the line number
report_transformer_warning(
"Assigning to value twice inside `if` block,"
" taking the last value (first value is ignored)",
self.filename, node.lineno + self.starting_line,
self.lines[node.lineno])
if self.filename:
# TODO: Print the line number
report_transformer_warning(
"Assigning to value twice inside `if` block,"
" taking the last value (first value is ignored)",
self.filename, node.lineno + self.starting_line,
self.lines[node.lineno])
else:
warning(
"Assigning to value twice inside `if` block,"
" taking the last value (first value is ignored)")
seen[key] = stmt
orelse_seen = set()
for stmt in node.orelse:
key = ast.dump(stmt.targets[0])
if key in seen:
if key in orelse_seen:
report_transformer_warning(
"Assigning to value twice inside `else` block,"
" taking the last value (first value is ignored)",
self.filename, node.lineno + self.starting_line,
self.lines[node.lineno])
if self.filename:
report_transformer_warning(
"Assigning to value twice inside `else` block,"
" taking the last value (first value is ignored)",
self.filename, node.lineno + self.starting_line,
self.lines[node.lineno])
else:
warning(
"Assigning to value twice inside `else` block,"
" taking the last value (first value is ignored)")
orelse_seen.add(key)
seen[key].value = ast.Call(
ast.Name("phi", ast.Load()),
[ast.List([stmt.value, seen[key].value],
ast.Load()), node.test],
[])
else:
report_transformer_warning(
"NOT IMPLEMENTED: Assigning to a variable once in"
" `else` block (not in then block)",
self.filename, node.lineno + self.starting_line,
self.lines[node.lineno])
if self.filename:
report_transformer_warning(
"NOT IMPLEMENTED: Assigning to a variable once in"
" `else` block (not in then block)",
self.filename, node.lineno + self.starting_line,
self.lines[node.lineno])
else:
warning(
"NOT IMPLEMENTED: Assigning to a variable once in"
" `else` block (not in then block)")
raise NotImplementedError()
return [node for node in seen.values()]

Expand Down Expand Up @@ -195,8 +214,12 @@ def combinational(defn_env: dict, fn: types.FunctionType):
tree, renamed_args = convert_tree_to_ssa(tree, defn_env)
tree = FunctionToCircuitDefTransformer(renamed_args).visit(tree)
tree = ast.fix_missing_locations(tree)
tree = IfTransformer(inspect.getsourcefile(fn),
inspect.getsourcelines(fn)).visit(tree)
filename = None
lines = None
if get_debug_mode():
filename = inspect.getsourcefile(fn)
lines = inspect.getsourcelines(fn)
tree = IfTransformer(filename, lines).visit(tree)
tree = ast.fix_missing_locations(tree)
tree.decorator_list = ast_utils.filter_decorator(
combinational, tree.decorator_list, defn_env)
Expand All @@ -213,9 +236,10 @@ def combinational(defn_env: dict, fn: types.FunctionType):
debug(source)
circuit_def = ast_utils.compile_function_to_file(tree, fn.__name__,
defn_env)
circuit_def.debug_info = debug_info(circuit_def.debug_info.filename,
circuit_def.debug_info.lineno,
inspect.getmodule(fn))
if get_debug_mode() and getattr(circuit_def, "debug_info", False):
circuit_def.debug_info = debug_info(circuit_def.debug_info.filename,
circuit_def.debug_info.lineno,
inspect.getmodule(fn))

@functools.wraps(fn)
def func(*args, **kwargs):
Expand Down
12 changes: 7 additions & 5 deletions magma/syntax/sequential.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import functools
import magma as m
from magma.ssa import convert_tree_to_ssa
from magma.config import get_debug_mode
from collections import Counter


Expand Down Expand Up @@ -268,8 +269,8 @@ def visit_Name(self, node):


def _sequential(defn_env: dict, cls):
if not inspect.isclass(cls):
raise ValueError("sequential decorator only works with classes")
# if not inspect.isclass(cls):
# raise ValueError("sequential decorator only works with classes")

initial_value_map = get_initial_value_map(cls.__init__, defn_env)

Expand Down Expand Up @@ -355,9 +356,10 @@ def _sequential(defn_env: dict, cls):
ast.parse("from mantle import DefineRegister").body[0],
] + tree.body)
circuit_def = ast_utils.compile_function_to_file(tree, cls.__name__, defn_env)
circuit_def.debug_info = debug_info(circuit_def.debug_info.filename,
circuit_def.debug_info.lineno,
inspect.getmodule(cls))
if get_debug_mode() and getattr(circuit_def, "debug_info", False):
circuit_def.debug_info = debug_info(circuit_def.debug_info.filename,
circuit_def.debug_info.lineno,
inspect.getmodule(cls))

return circuit_def

Expand Down

0 comments on commit c3030d5

Please sign in to comment.