CIRCT 22.0.0git
Loading...
Searching...
No Matches
CutRewriter.h
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header file defines a general cut-based rewriting framework for
10// combinational logic optimization. The framework uses NPN-equivalence matching
11// with area and delay metrics to rewrite cuts (subgraphs) in combinational
12// circuits with optimal patterns.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef CIRCT_DIALECT_SYNTH_TRANSFORMS_CUT_REWRITER_H
17#define CIRCT_DIALECT_SYNTH_TRANSFORMS_CUT_REWRITER_H
18
20#include "circt/Support/LLVM.h"
22#include "mlir/IR/Operation.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/Support/LogicalResult.h"
27#include "llvm/Support/raw_ostream.h"
28#include <memory>
29#include <optional>
30
31namespace circt {
32namespace synth {
33// Type for representing delays in the circuit. It's user's responsibility to
34// use consistent units, i.e., all delays should be in the same unit (usually
35// femtoseconds, but not limited to it).
36using DelayType = int64_t;
37
38/// Maximum number of inputs supported for truth table generation.
39/// This limit prevents excessive memory usage as truth table size grows
40/// exponentially with the number of inputs (2^n entries).
41static constexpr unsigned maxTruthTableInputs = 16;
42
43// This is a helper function to sort operations topologically in a logic
44// network. This is necessary for cut rewriting to ensure that operations are
45// processed in the correct order, respecting dependencies.
46LogicalResult topologicallySortLogicNetwork(mlir::Operation *op);
47
48// Get the truth table for a specific operation within a block.
49// Block must be a SSACFG or topologically sorted.
50FailureOr<BinaryTruthTable> getTruthTable(ValueRange values, Block *block);
51
52//===----------------------------------------------------------------------===//
53// Cut Data Structures
54//===----------------------------------------------------------------------===//
55
56// Forward declarations
58class CutRewriter;
59class CutEnumerator;
62
63/// Result of matching a cut against a pattern.
64///
65/// This structure contains the area and per-input delay information
66/// computed during pattern matching.
67///
68/// The delays can be stored in two ways:
69/// 1. As a reference to static/cached data (e.g., tech library delays)
70/// - Use setDelayRef() for zero-cost reference (no allocation)
71/// 2. As owned dynamic data (e.g., computed SOP delays)
72/// - Use setOwnedDelays() to transfer ownership
73///
75 /// Area cost of implementing this cut with the pattern.
76 double area = 0.0;
77
78 /// Default constructor.
79 MatchResult() = default;
80
81 /// Constructor with area and delays (by reference).
82 MatchResult(double area, ArrayRef<DelayType> delays)
83 : area(area), borrowedDelays(delays) {}
84
85 /// Set delays by reference (zero-cost for static/cached delays).
86 /// The caller must ensure the referenced data remains valid.
87 void setDelayRef(ArrayRef<DelayType> delays) { borrowedDelays = delays; }
88
89 /// Set delays by transferring ownership (for dynamically computed delays).
90 /// This moves the data into internal storage.
91 void setOwnedDelays(SmallVector<DelayType, 6> delays) {
92 ownedDelays.emplace(std::move(delays));
93 borrowedDelays = {};
94 }
95
96 /// Get all delays as an ArrayRef.
97 ArrayRef<DelayType> getDelays() const {
98 return ownedDelays.has_value() ? ArrayRef<DelayType>(*ownedDelays)
100 }
101
102private:
103 /// Borrowed delays (used when ownedDelays is empty).
104 /// Points to external data provided via setDelayRef().
105 ArrayRef<DelayType> borrowedDelays;
106
107 /// Owned delays (used when present).
108 /// Only allocated when setOwnedDelays() is called. When empty (std::nullopt),
109 /// moving this MatchResult avoids constructing/moving the SmallVector,
110 /// achieving zero-cost abstraction for the common case (borrowed delays).
111 std::optional<SmallVector<DelayType, 6>> ownedDelays;
112};
113
114/// Represents a cut that has been successfully matched to a rewriting pattern.
115///
116/// This class encapsulates the result of matching a cut against a rewriting
117/// pattern during optimization. It stores the matched pattern, the
118/// cut that was matched, and timing information needed for optimization.
120private:
121 const CutRewritePattern *pattern = nullptr; ///< The matched library pattern
122 SmallVector<DelayType, 1>
123 arrivalTimes; ///< Arrival times of outputs from this pattern
124 double area = 0.0; ///< Area cost of this pattern
125
126public:
127 /// Default constructor creates an invalid matched pattern.
128 MatchedPattern() = default;
129
130 /// Constructor for a valid matched pattern.
132 SmallVector<DelayType, 1> arrivalTimes, double area)
133 : pattern(pattern), arrivalTimes(std::move(arrivalTimes)), area(area) {}
134
135 /// Get the arrival time of signals through this pattern.
136 DelayType getArrivalTime(unsigned outputIndex) const;
137 ArrayRef<DelayType> getArrivalTimes() const;
139
140 /// Get the library pattern that was matched.
141 const CutRewritePattern *getPattern() const;
142
143 /// Get the area cost of using this pattern.
144 double getArea() const;
145};
146
147/// Represents a cut in the combinational logic network.
148///
149/// A cut is a subset of nodes in the combinational logic that forms a complete
150/// subgraph with a single output. It represents a portion of the circuit that
151/// can potentially be replaced with a single library gate or pattern.
152///
153/// The cut contains:
154/// - Input values: The boundary between the cut and the rest of the circuit
155/// - Operations: The logic operations within the cut boundary
156/// - Root operation: The output-driving operation of the cut
157///
158/// Cuts are used in combinational logic optimization to identify regions that
159/// can be optimized and replaced with more efficient implementations.
160class Cut {
161 /// Cached truth table for this cut.
162 /// Computed lazily when first accessed to avoid unnecessary computation.
163 mutable std::optional<BinaryTruthTable> truthTable;
164
165 /// Cached NPN canonical form for this cut.
166 /// Computed lazily from the truth table when first accessed.
167 mutable std::optional<NPNClass> npnClass;
168
169 std::optional<MatchedPattern> matchedPattern;
170
171public:
172 /// External inputs to this cut (cut boundary).
173 /// These are the values that flow into the cut from outside.
174 llvm::SmallSetVector<mlir::Value, 4> inputs;
175
176 /// Operations contained within this cut.
177 /// Stored in topological order with the root operation at the end.
178 llvm::SmallSetVector<mlir::Operation *, 4> operations;
179
180 /// Check if this cut represents a trivial cut.
181 /// A trivial cut has no internal operations and exactly one input.
182 bool isTrivialCut() const;
183
184 /// Get the root operation of this cut.
185 /// The root operation produces the output of the cut.
186 mlir::Operation *getRoot() const;
187
188 void dump(llvm::raw_ostream &os) const;
189
190 /// Merge this cut with another cut to form a new cut.
191 /// The new cut combines the operations from both cuts with the given root.
192 Cut mergeWith(const Cut &other, Operation *root) const;
193 Cut reRoot(Operation *root) const;
194
195 /// Get the number of inputs to this cut.
196 unsigned getInputSize() const;
197
198 /// Get the number of operations in this cut.
199 unsigned getCutSize() const;
200
201 /// Get the number of outputs from root operation.
202 unsigned getOutputSize() const;
203
204 /// Get the truth table for this cut.
205 /// The truth table represents the boolean function computed by this cut.
206 const BinaryTruthTable &getTruthTable() const;
207
208 /// Get the NPN canonical form for this cut.
209 /// This is used for efficient pattern matching against library components.
210 const NPNClass &getNPNClass() const;
211
212 /// Get the permutated inputs for this cut based on the given pattern NPN.
213 void getPermutatedInputs(const NPNClass &patternNPN,
214 SmallVectorImpl<Value> &permutedInputs) const;
215
216 /// Matched pattern for this cut.
220
221 /// Get the matched pattern for this cut.
222 const std::optional<MatchedPattern> &getMatchedPattern() const {
223 return matchedPattern;
224 }
225};
226
227/// Manages a collection of cuts for a single logic node using priority cuts
228/// algorithm.
229///
230/// Each node in the combinational logic network can have multiple cuts
231/// representing different ways to group it with surrounding logic. The CutSet
232/// manages these cuts and selects the best one based on the optimization
233/// strategy (area or timing).
234///
235/// The priority cuts algorithm maintains a bounded set of the most promising
236/// cuts to avoid exponential explosion while ensuring good optimization
237/// results.
238class CutSet {
239private:
240 llvm::SmallVector<Cut, 4> cuts; ///< Collection of cuts for this node
241 Cut *bestCut = nullptr;
242 bool isFrozen = false; ///< Whether cut set is finalized
243
244public:
245 /// Check if this cut set has a valid matched pattern.
246 bool isMatched() const { return bestCut; }
247
248 /// Get the cut associated with the best matched pattern.
249 Cut *getBestMatchedCut() const;
250
251 /// Finalize the cut set by removing duplicates and selecting the best
252 /// pattern.
253 ///
254 /// This method:
255 /// 1. Removes duplicate cuts based on inputs and root operation
256 /// 2. Limits the number of cuts to prevent exponential growth
257 /// 3. Matches each cut against available patterns
258 /// 4. Selects the best pattern based on the optimization strategy
259 void finalize(
260 const CutRewriterOptions &options,
261 llvm::function_ref<std::optional<MatchedPattern>(const Cut &)> matchCut);
262
263 /// Get the number of cuts in this set.
264 unsigned size() const;
265
266 /// Add a new cut to this set.
267 /// NOTE: The cut set must not be frozen
268 void addCut(Cut cut);
269
270 /// Get read-only access to all cuts in this set.
271 ArrayRef<Cut> getCuts() const;
272};
273
274/// Configuration options for the cut-based rewriting algorithm.
275///
276/// These options control various aspects of the rewriting process including
277/// optimization strategy, resource limits, and algorithmic parameters.
279 /// Optimization strategy (area vs. timing).
281
282 /// Maximum number of inputs allowed for any cut.
283 /// Larger cuts provide more optimization opportunities but increase
284 /// computational complexity exponentially.
286
287 /// Maximum number of cuts to maintain per logic node.
288 /// The priority cuts algorithm keeps only the most promising cuts
289 /// to prevent exponential explosion.
291
292 /// Fail if there is a root operation that has no matching pattern.
293 bool allowNoMatch = false;
294
295 /// Put arrival times to rewritten operations.
296 bool attachDebugTiming = false;
297
298 /// Run priority cuts enumeration and dump the cut sets.
299 bool testPriorityCuts = false;
300};
301
302//===----------------------------------------------------------------------===//
303// Cut Enumeration Engine
304//===----------------------------------------------------------------------===//
305
306/// Cut enumeration engine for combinational logic networks.
307///
308/// The CutEnumerator is responsible for generating cuts for each node in a
309/// combinational logic network. It uses a priority cuts algorithm to maintain a
310/// bounded set of promising cuts while avoiding exponential explosion.
311///
312/// The enumeration process works by:
313/// 1. Visiting nodes in topological order
314/// 2. For each node, combining cuts from its inputs
315/// 3. Matching generated cuts against available patterns
316/// 4. Maintaining only the most promising cuts per node
318public:
319 /// Constructor for cut enumerator.
321
322 /// Enumerate cuts for all nodes in the given module.
323 ///
324 /// This is the main entry point that orchestrates the cut enumeration
325 /// process. It visits all operations in the module and generates cuts
326 /// for combinational logic operations.
327 LogicalResult enumerateCuts(
328 Operation *topOp,
329 llvm::function_ref<std::optional<MatchedPattern>(const Cut &)> matchCut =
330 [](const Cut &) { return std::nullopt; });
331
332 /// Create a new cut set for a value.
333 /// The value must not already have a cut set.
334 CutSet *createNewCutSet(Value value);
335
336 /// Get the cut set for a specific value.
337 /// If not found, it means no cuts have been generated for this value yet.
338 /// In that case return a trivial cut set.
339 const CutSet *getCutSet(Value value);
340
341 /// Move ownership of all cut sets to caller.
342 /// After calling this, the enumerator is left in an empty state.
343 llvm::MapVector<Value, std::unique_ptr<CutSet>> takeVector();
344
345 /// Clear all cut sets and reset the enumerator.
346 void clear();
347
348 void dump() const;
349 const llvm::MapVector<Value, std::unique_ptr<CutSet>> &getCutSets() const {
350 return cutSets;
351 }
352
353private:
354 /// Visit a single operation and generate cuts for it.
355 LogicalResult visit(Operation *op);
356
357 /// Visit a combinational logic operation and generate cuts.
358 /// This handles the core cut enumeration logic for operations
359 /// like AND, OR, XOR, etc.
360 LogicalResult visitLogicOp(Operation *logicOp);
361
362 /// Maps values to their associated cut sets.
363 llvm::MapVector<Value, std::unique_ptr<CutSet>> cutSets;
364
365 /// Configuration options for cut enumeration.
367
368 /// Function to match cuts against available patterns.
369 /// Set during enumeration and used when finalizing cut sets.
370 llvm::function_ref<std::optional<MatchedPattern>(const Cut &)> matchCut;
371};
372
373/// Base class for cut rewriting patterns used in combinational logic
374/// optimization.
375///
376/// A CutRewritePattern represents a library component or optimization pattern
377/// that can replace cuts in the combinational logic network. Each pattern
378/// defines:
379/// - How to recognize matching cuts and compute area/delay metrics
380/// - How to transform/replace the matched cuts
381///
382/// Patterns can use truth table matching for efficient recognition or
383/// implement custom matching logic for more complex cases.
385 CutRewritePattern(mlir::MLIRContext *context) : context(context) {}
386 /// Virtual destructor for base class.
387 virtual ~CutRewritePattern() = default;
388
389 /// Check if a cut matches this pattern and compute area/delay metrics.
390 ///
391 /// This method is called to determine if a cut can be replaced by this
392 /// pattern. If the cut matches, it should return a MatchResult containing
393 /// the area and per-input delays for this specific cut.
394 ///
395 /// If useTruthTableMatcher() returns true, this method is only
396 /// called for cuts with matching truth tables.
397 virtual std::optional<MatchResult> match(CutEnumerator &enumerator,
398 const Cut &cut) const = 0;
399
400 /// Specify truth tables that this pattern can match.
401 ///
402 /// If this method returns true, the pattern matcher will use truth table
403 /// comparison for efficient pre-filtering. Only cuts with matching truth
404 /// tables will be passed to the match() method. If it returns false, the
405 /// pattern will be checked against all cuts regardless of their truth tables.
406 /// This is useful for patterns that match regardless of their truth tables,
407 /// such as LUT-based patterns.
408 virtual bool
409 useTruthTableMatcher(SmallVectorImpl<NPNClass> &matchingNPNClasses) const;
410
411 /// Return a new operation that replaces the matched cut.
412 ///
413 /// Unlike MLIR's RewritePattern framework which allows arbitrary in-place
414 /// modifications, this method creates a new operation to replace the matched
415 /// cut rather than modifying existing operations. This constraint exists
416 /// because the cut enumerator maintains references to operations throughout
417 /// the circuit, making it safe to only replace the root operation of each
418 /// cut while preserving all other operations unchanged.
419 virtual FailureOr<Operation *> rewrite(mlir::OpBuilder &builder,
420 CutEnumerator &enumerator,
421 const Cut &cut) const = 0;
422
423 /// Get the number of outputs this pattern produces.
424 virtual unsigned getNumOutputs() const = 0;
425
426 /// Get the name of this pattern. Used for debugging.
427 virtual StringRef getPatternName() const { return "<unnamed>"; }
428
429 /// Get location for this pattern(optional).
430 virtual LocationAttr getLoc() const { return mlir::UnknownLoc::get(context); }
431
432 mlir::MLIRContext *getContext() const { return context; }
433
434private:
435 mlir::MLIRContext *context;
436};
437
438/// Manages a collection of rewriting patterns for combinational logic
439/// optimization.
440///
441/// This class organizes and provides efficient access to rewriting patterns
442/// used during cut-based optimization. It maintains:
443/// - A collection of all available patterns
444/// - Fast lookup tables for truth table-based matching
445/// - Separation of truth table vs. custom matching patterns
446///
447/// The pattern set is used by the CutRewriter to find suitable replacements
448/// for cuts in the combinational logic network.
450public:
451 /// Constructor that takes ownership of the provided patterns.
452 ///
453 /// During construction, patterns are analyzed and organized for efficient
454 /// lookup. Truth table matchers are indexed by their NPN canonical forms.
456 llvm::SmallVector<std::unique_ptr<CutRewritePattern>, 4> patterns);
457
458private:
459 /// Owned collection of all rewriting patterns.
460 llvm::SmallVector<std::unique_ptr<CutRewritePattern>, 4> patterns;
461
462 /// Fast lookup table mapping NPN canonical forms to matching patterns.
463 /// Each entry maps a truth table and input size to patterns that can handle
464 /// it.
465 DenseMap<std::pair<APInt, unsigned>,
466 SmallVector<std::pair<NPNClass, const CutRewritePattern *>>>
468
469 /// Patterns that use custom matching logic instead of NPN lookup.
470 /// These patterns are checked against every cut.
471 SmallVector<const CutRewritePattern *, 4> nonNPNPatterns;
472
473 /// CutRewriter needs access to internal data structures for pattern matching.
474 friend class CutRewriter;
475};
476
477/// Main cut-based rewriting algorithm for combinational logic optimization.
478///
479/// The CutRewriter implements a cut-based rewriting algorithm that:
480/// 1. Enumerates cuts in the combinational logic network using a priority cuts
481/// algorithm
482/// 2. Matches cuts against available rewriting patterns
483/// 3. Selects optimal patterns based on area or timing objectives
484/// 4. Rewrites the circuit using the selected patterns
485///
486/// The algorithm processes the network in topological order, building up cut
487/// sets for each node and selecting the best implementation based on the
488/// specified optimization strategy.
489///
490/// Usage example:
491/// ```cpp
492/// CutRewriterOptions options;
493/// options.strategy = OptimizationStrategy::Area;
494/// options.maxCutInputSize = 4;
495/// options.maxCutSizePerRoot = 8;
496///
497/// CutRewritePatternSet patterns(std::move(optimizationPatterns));
498/// CutRewriter rewriter(module, options, patterns);
499///
500/// if (failed(rewriter.run())) {
501/// // Handle rewriting failure
502/// }
503/// ```
505public:
506 /// Constructor for the cut rewriter.
509
510 /// Execute the complete cut-based rewriting algorithm.
511 ///
512 /// This method orchestrates the entire rewriting process:
513 /// 1. Enumerate cuts for all nodes in the combinational logic
514 /// 2. Match cuts against available patterns
515 /// 3. Select optimal patterns based on strategy
516 /// 4. Rewrite the circuit with selected patterns
517 LogicalResult run(Operation *topOp);
518
519private:
520 /// Enumerate cuts for all nodes in the given module.
521 /// Note: This preserves module boundaries and does not perform
522 /// rewriting across the hierarchy.
523 LogicalResult enumerateCuts(Operation *topOp);
524
525 /// Find patterns that match a cut's truth table.
526 ArrayRef<std::pair<NPNClass, const CutRewritePattern *>>
527 getMatchingPatternsFromTruthTable(const Cut &cut) const;
528
529 /// Match a cut against available patterns and compute arrival time.
530 std::optional<MatchedPattern> patternMatchCut(const Cut &cut);
531
532 /// Perform the actual circuit rewriting using selected patterns.
533 LogicalResult runBottomUpRewrite(Operation *topOp);
534
535 /// Configuration options
537
538 /// Available rewriting patterns
540
542};
543
544} // namespace synth
545} // namespace circt
546
547#endif // CIRCT_DIALECT_SYNTH_TRANSFORMS_CUT_REWRITER_H
RewritePatternSet pattern
Cut enumeration engine for combinational logic networks.
LogicalResult visit(Operation *op)
Visit a single operation and generate cuts for it.
const CutRewriterOptions & options
Configuration options for cut enumeration.
llvm::MapVector< Value, std::unique_ptr< CutSet > > cutSets
Maps values to their associated cut sets.
LogicalResult enumerateCuts(Operation *topOp, llvm::function_ref< std::optional< MatchedPattern >(const Cut &)> matchCut=[](const Cut &) { return std::nullopt;})
Enumerate cuts for all nodes in the given module.
const llvm::MapVector< Value, std::unique_ptr< CutSet > > & getCutSets() const
void clear()
Clear all cut sets and reset the enumerator.
llvm::function_ref< std::optional< MatchedPattern >(const Cut &)> matchCut
Function to match cuts against available patterns.
LogicalResult visitLogicOp(Operation *logicOp)
Visit a combinational logic operation and generate cuts.
llvm::MapVector< Value, std::unique_ptr< CutSet > > takeVector()
Move ownership of all cut sets to caller.
CutSet * createNewCutSet(Value value)
Create a new cut set for a value.
const CutSet * getCutSet(Value value)
Get the cut set for a specific value.
Manages a collection of rewriting patterns for combinational logic optimization.
llvm::SmallVector< std::unique_ptr< CutRewritePattern >, 4 > patterns
Owned collection of all rewriting patterns.
SmallVector< const CutRewritePattern *, 4 > nonNPNPatterns
Patterns that use custom matching logic instead of NPN lookup.
DenseMap< std::pair< APInt, unsigned >, SmallVector< std::pair< NPNClass, const CutRewritePattern * > > > npnToPatternMap
Fast lookup table mapping NPN canonical forms to matching patterns.
Main cut-based rewriting algorithm for combinational logic optimization.
const CutRewriterOptions & options
Configuration options.
ArrayRef< std::pair< NPNClass, const CutRewritePattern * > > getMatchingPatternsFromTruthTable(const Cut &cut) const
Find patterns that match a cut's truth table.
std::optional< MatchedPattern > patternMatchCut(const Cut &cut)
Match a cut against available patterns and compute arrival time.
LogicalResult enumerateCuts(Operation *topOp)
Enumerate cuts for all nodes in the given module.
LogicalResult run(Operation *topOp)
Execute the complete cut-based rewriting algorithm.
const CutRewritePatternSet & patterns
Available rewriting patterns.
CutEnumerator cutEnumerator
CutRewriter(const CutRewriterOptions &options, CutRewritePatternSet &patterns)
Constructor for the cut rewriter.
LogicalResult runBottomUpRewrite(Operation *topOp)
Perform the actual circuit rewriting using selected patterns.
Manages a collection of cuts for a single logic node using priority cuts algorithm.
Cut * getBestMatchedCut() const
Get the cut associated with the best matched pattern.
llvm::SmallVector< Cut, 4 > cuts
Collection of cuts for this node.
void addCut(Cut cut)
Add a new cut to this set.
unsigned size() const
Get the number of cuts in this set.
void finalize(const CutRewriterOptions &options, llvm::function_ref< std::optional< MatchedPattern >(const Cut &)> matchCut)
Finalize the cut set by removing duplicates and selecting the best pattern.
bool isMatched() const
Check if this cut set has a valid matched pattern.
bool isFrozen
Whether cut set is finalized.
ArrayRef< Cut > getCuts() const
Get read-only access to all cuts in this set.
Represents a cut in the combinational logic network.
std::optional< NPNClass > npnClass
Cached NPN canonical form for this cut.
std::optional< MatchedPattern > matchedPattern
const std::optional< MatchedPattern > & getMatchedPattern() const
Get the matched pattern for this cut.
llvm::SmallSetVector< mlir::Operation *, 4 > operations
Operations contained within this cut.
unsigned getOutputSize() const
Get the number of outputs from root operation.
void getPermutatedInputs(const NPNClass &patternNPN, SmallVectorImpl< Value > &permutedInputs) const
Get the permutated inputs for this cut based on the given pattern NPN.
const NPNClass & getNPNClass() const
Get the NPN canonical form for this cut.
mlir::Operation * getRoot() const
Get the root operation of this cut.
llvm::SmallSetVector< mlir::Value, 4 > inputs
External inputs to this cut (cut boundary).
void dump(llvm::raw_ostream &os) const
const BinaryTruthTable & getTruthTable() const
Get the truth table for this cut.
std::optional< BinaryTruthTable > truthTable
Cached truth table for this cut.
Cut mergeWith(const Cut &other, Operation *root) const
Merge this cut with another cut to form a new cut.
unsigned getInputSize() const
Get the number of inputs to this cut.
void setMatchedPattern(MatchedPattern pattern)
Matched pattern for this cut.
unsigned getCutSize() const
Get the number of operations in this cut.
bool isTrivialCut() const
Check if this cut represents a trivial cut.
Cut reRoot(Operation *root) const
Represents a cut that has been successfully matched to a rewriting pattern.
double area
Area cost of this pattern.
DelayType getArrivalTime(unsigned outputIndex) const
Get the arrival time of signals through this pattern.
ArrayRef< DelayType > getArrivalTimes() const
const CutRewritePattern * pattern
The matched library pattern.
MatchedPattern(const CutRewritePattern *pattern, SmallVector< DelayType, 1 > arrivalTimes, double area)
Constructor for a valid matched pattern.
DelayType getWorstOutputArrivalTime() const
double getArea() const
Get the area cost of using this pattern.
MatchedPattern()=default
Default constructor creates an invalid matched pattern.
const CutRewritePattern * getPattern() const
Get the library pattern that was matched.
SmallVector< DelayType, 1 > arrivalTimes
Arrival times of outputs from this pattern.
OptimizationStrategy
Optimization strategy.
Definition SynthPasses.h:24
FailureOr< BinaryTruthTable > getTruthTable(ValueRange values, Block *block)
int64_t DelayType
Definition CutRewriter.h:36
static constexpr unsigned maxTruthTableInputs
Maximum number of inputs supported for truth table generation.
Definition CutRewriter.h:41
LogicalResult topologicallySortLogicNetwork(mlir::Operation *op)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition synth.py:1
Represents a boolean function as a truth table.
Definition NPNClass.h:38
Represents the canonical form of a boolean function under NPN equivalence.
Definition NPNClass.h:103
Base class for cut rewriting patterns used in combinational logic optimization.
virtual StringRef getPatternName() const
Get the name of this pattern. Used for debugging.
virtual FailureOr< Operation * > rewrite(mlir::OpBuilder &builder, CutEnumerator &enumerator, const Cut &cut) const =0
Return a new operation that replaces the matched cut.
virtual ~CutRewritePattern()=default
Virtual destructor for base class.
virtual bool useTruthTableMatcher(SmallVectorImpl< NPNClass > &matchingNPNClasses) const
Specify truth tables that this pattern can match.
virtual std::optional< MatchResult > match(CutEnumerator &enumerator, const Cut &cut) const =0
Check if a cut matches this pattern and compute area/delay metrics.
mlir::MLIRContext * getContext() const
mlir::MLIRContext * context
CutRewritePattern(mlir::MLIRContext *context)
virtual unsigned getNumOutputs() const =0
Get the number of outputs this pattern produces.
virtual LocationAttr getLoc() const
Get location for this pattern(optional).
Configuration options for the cut-based rewriting algorithm.
unsigned maxCutInputSize
Maximum number of inputs allowed for any cut.
unsigned maxCutSizePerRoot
Maximum number of cuts to maintain per logic node.
bool allowNoMatch
Fail if there is a root operation that has no matching pattern.
bool attachDebugTiming
Put arrival times to rewritten operations.
OptimizationStrategy strategy
Optimization strategy (area vs. timing).
bool testPriorityCuts
Run priority cuts enumeration and dump the cut sets.
Result of matching a cut against a pattern.
Definition CutRewriter.h:74
void setDelayRef(ArrayRef< DelayType > delays)
Set delays by reference (zero-cost for static/cached delays).
Definition CutRewriter.h:87
MatchResult()=default
Default constructor.
void setOwnedDelays(SmallVector< DelayType, 6 > delays)
Set delays by transferring ownership (for dynamically computed delays).
Definition CutRewriter.h:91
double area
Area cost of implementing this cut with the pattern.
Definition CutRewriter.h:76
ArrayRef< DelayType > borrowedDelays
Borrowed delays (used when ownedDelays is empty).
std::optional< SmallVector< DelayType, 6 > > ownedDelays
Owned delays (used when present).
MatchResult(double area, ArrayRef< DelayType > delays)
Constructor with area and delays (by reference).
Definition CutRewriter.h:82
ArrayRef< DelayType > getDelays() const
Get all delays as an ArrayRef.
Definition CutRewriter.h:97