Ticket #119 (assigned defect)

Opened 2 months ago

Last modified 3 weeks ago

request compile time value without raising error (allow constant folding)

Reported by: robertwb Assigned to: scoder (accepted)
Priority: major Milestone: wishlist
Component: Code Generation Version:
Keywords: Cc:

Description

Often one wants to try and obtain the compile-time value of an expression, but if it can't be decided then that's just fine. Currently it creates an error.

Change History

12/12/2008 12:50:02 AM changed by scoder

I think the best way to solve this would be to always calculate the values of constant expressions somewhere between the analysis and code generation phase. A dedicated transform would be good for this. It could either replace expressions with their constant result node (e.g. with an IntNode of the result type), or it could at least add a const_result attribute to each ExprNode that would either be None (no constant result) or hold a tuple (result_type, Python value). A tuple is better than a plain value here, as None is a valid result value. Maybe a mixture of both approaches is doable. The code generation phase could then check directly if a node has a constant value and decide if it can generate optimal code for the constant case.

12/12/2008 12:53:03 AM changed by scoder

I always forget that None is just a value. The value for "not a constant" could obviously be any dedicated object. So a tuple saying "this is the constant value" isn't required.

12/13/2008 06:38:31 AM changed by scoder

  • owner changed from somebody to scoder.
  • status changed from new to assigned.
  • summary changed from request compile time value without raising error to request compile time value without raising error (allow constant folding).

12/13/2008 02:00:52 PM changed by scoder

Initial implementation is here:

http://hg.cython.org/cython-devel/rev/8a2e7b51e770

The new ConstantFolding transform walks through all ExprNodes, calculates their constant value and stores it in node.constant_value. The constant_result attribute is initially set to ExprNodes.constant_value_not_set and the transform replaces it by either ExprNodes.not_a_constant or the constant result of the subexpression. The code generation phase (or intermediate transforms) can then use that result instead of generating code for the original subexpression.

The transform does not currently replace nodes by a constant node, this would require: - a mapping from the C result type (pyrex type) to an ExprNode that can represent this value - a way to initialise this node after the type analysis phase, including things like cached constant values for integers etc.