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 /// Get arrival times for each input of this cut.
217 /// Returns failure if any input doesn't have a valid matched pattern.
218 LogicalResult getInputArrivalTimes(CutEnumerator &enumerator,
219 SmallVectorImpl<DelayType> &results) const;
220
221 /// Matched pattern for this cut.
225
226 /// Get the matched pattern for this cut.
227 const std::optional<MatchedPattern> &getMatchedPattern() const {
228 return matchedPattern;
229 }
230};
231
232/// Manages a collection of cuts for a single logic node using priority cuts
233/// algorithm.
234///
235/// Each node in the combinational logic network can have multiple cuts
236/// representing different ways to group it with surrounding logic. The CutSet
237/// manages these cuts and selects the best one based on the optimization
238/// strategy (area or timing).
239///
240/// The priority cuts algorithm maintains a bounded set of the most promising
241/// cuts to avoid exponential explosion while ensuring good optimization
242/// results.
243class CutSet {
244private:
245 llvm::SmallVector<Cut, 4> cuts; ///< Collection of cuts for this node
246 Cut *bestCut = nullptr;
247 bool isFrozen = false; ///< Whether cut set is finalized
248
249public:
250 /// Check if this cut set has a valid matched pattern.
251 bool isMatched() const { return bestCut; }
252
253 /// Get the cut associated with the best matched pattern.
254 Cut *getBestMatchedCut() const;
255
256 /// Finalize the cut set by removing duplicates and selecting the best
257 /// pattern.
258 ///
259 /// This method:
260 /// 1. Removes duplicate cuts based on inputs and root operation
261 /// 2. Limits the number of cuts to prevent exponential growth
262 /// 3. Matches each cut against available patterns
263 /// 4. Selects the best pattern based on the optimization strategy
264 void finalize(
265 const CutRewriterOptions &options,
266 llvm::function_ref<std::optional<MatchedPattern>(const Cut &)> matchCut);
267
268 /// Get the number of cuts in this set.
269 unsigned size() const;
270
271 /// Add a new cut to this set.
272 /// NOTE: The cut set must not be frozen
273 void addCut(Cut cut);
274
275 /// Get read-only access to all cuts in this set.
276 ArrayRef<Cut> getCuts() const;
277};
278
279/// Configuration options for the cut-based rewriting algorithm.
280///
281/// These options control various aspects of the rewriting process including
282/// optimization strategy, resource limits, and algorithmic parameters.
284 /// Optimization strategy (area vs. timing).
286
287 /// Maximum number of inputs allowed for any cut.
288 /// Larger cuts provide more optimization opportunities but increase
289 /// computational complexity exponentially.
291
292 /// Maximum number of cuts to maintain per logic node.
293 /// The priority cuts algorithm keeps only the most promising cuts
294 /// to prevent exponential explosion.
296
297 /// Fail if there is a root operation that has no matching pattern.
298 bool allowNoMatch = false;
299
300 /// Put arrival times to rewritten operations.
301 bool attachDebugTiming = false;
302
303 /// Run priority cuts enumeration and dump the cut sets.
304 bool testPriorityCuts = false;
305};
306
307//===----------------------------------------------------------------------===//
308// Cut Enumeration Engine
309//===----------------------------------------------------------------------===//
310
311/// Cut enumeration engine for combinational logic networks.
312///
313/// The CutEnumerator is responsible for generating cuts for each node in a
314/// combinational logic network. It uses a priority cuts algorithm to maintain a
315/// bounded set of promising cuts while avoiding exponential explosion.
316///
317/// The enumeration process works by:
318/// 1. Visiting nodes in topological order
319/// 2. For each node, combining cuts from its inputs
320/// 3. Matching generated cuts against available patterns
321/// 4. Maintaining only the most promising cuts per node
323public:
324 /// Constructor for cut enumerator.
326
327 /// Enumerate cuts for all nodes in the given module.
328 ///
329 /// This is the main entry point that orchestrates the cut enumeration
330 /// process. It visits all operations in the module and generates cuts
331 /// for combinational logic operations.
332 LogicalResult enumerateCuts(
333 Operation *topOp,
334 llvm::function_ref<std::optional<MatchedPattern>(const Cut &)> matchCut =
335 [](const Cut &) { return std::nullopt; });
336
337 /// Create a new cut set for a value.
338 /// The value must not already have a cut set.
339 CutSet *createNewCutSet(Value value);
340
341 /// Get the cut set for a specific value.
342 /// If not found, it means no cuts have been generated for this value yet.
343 /// In that case return a trivial cut set.
344 const CutSet *getCutSet(Value value);
345
346 /// Move ownership of all cut sets to caller.
347 /// After calling this, the enumerator is left in an empty state.
348 llvm::MapVector<Value, std::unique_ptr<CutSet>> takeVector();
349
350 /// Clear all cut sets and reset the enumerator.
351 void clear();
352
353 void dump() const;
354 const llvm::MapVector<Value, std::unique_ptr<CutSet>> &getCutSets() const {
355 return cutSets;
356 }
357
358private:
359 /// Visit a single operation and generate cuts for it.
360 LogicalResult visit(Operation *op);
361
362 /// Visit a combinational logic operation and generate cuts.
363 /// This handles the core cut enumeration logic for operations
364 /// like AND, OR, XOR, etc.
365 LogicalResult visitLogicOp(Operation *logicOp);
366
367 /// Maps values to their associated cut sets.
368 llvm::MapVector<Value, std::unique_ptr<CutSet>> cutSets;
369
370 /// Configuration options for cut enumeration.
372
373 /// Function to match cuts against available patterns.
374 /// Set during enumeration and used when finalizing cut sets.
375 llvm::function_ref<std::optional<MatchedPattern>(const Cut &)> matchCut;
376};
377
378/// Base class for cut rewriting patterns used in combinational logic
379/// optimization.
380///
381/// A CutRewritePattern represents a library component or optimization pattern
382/// that can replace cuts in the combinational logic network. Each pattern
383/// defines:
384/// - How to recognize matching cuts and compute area/delay metrics
385/// - How to transform/replace the matched cuts
386///
387/// Patterns can use truth table matching for efficient recognition or
388/// implement custom matching logic for more complex cases.
390 CutRewritePattern(mlir::MLIRContext *context) : context(context) {}
391 /// Virtual destructor for base class.
392 virtual ~CutRewritePattern() = default;
393
394 /// Check if a cut matches this pattern and compute area/delay metrics.
395 ///
396 /// This method is called to determine if a cut can be replaced by this
397 /// pattern. If the cut matches, it should return a MatchResult containing
398 /// the area and per-input delays for this specific cut.
399 ///
400 /// If useTruthTableMatcher() returns true, this method is only
401 /// called for cuts with matching truth tables.
402 virtual std::optional<MatchResult> match(CutEnumerator &enumerator,
403 const Cut &cut) const = 0;
404
405 /// Specify truth tables that this pattern can match.
406 ///
407 /// If this method returns true, the pattern matcher will use truth table
408 /// comparison for efficient pre-filtering. Only cuts with matching truth
409 /// tables will be passed to the match() method. If it returns false, the
410 /// pattern will be checked against all cuts regardless of their truth tables.
411 /// This is useful for patterns that match regardless of their truth tables,
412 /// such as LUT-based patterns.
413 virtual bool
414 useTruthTableMatcher(SmallVectorImpl<NPNClass> &matchingNPNClasses) const;
415
416 /// Return a new operation that replaces the matched cut.
417 ///
418 /// Unlike MLIR's RewritePattern framework which allows arbitrary in-place
419 /// modifications, this method creates a new operation to replace the matched
420 /// cut rather than modifying existing operations. This constraint exists
421 /// because the cut enumerator maintains references to operations throughout
422 /// the circuit, making it safe to only replace the root operation of each
423 /// cut while preserving all other operations unchanged.
424 virtual FailureOr<Operation *> rewrite(mlir::OpBuilder &builder,
425 CutEnumerator &enumerator,
426 const Cut &cut) const = 0;
427
428 /// Get the number of outputs this pattern produces.
429 virtual unsigned getNumOutputs() const = 0;
430
431 /// Get the name of this pattern. Used for debugging.
432 virtual StringRef getPatternName() const { return "<unnamed>"; }
433
434 /// Get location for this pattern(optional).
435 virtual LocationAttr getLoc() const { return mlir::UnknownLoc::get(context); }
436
437 mlir::MLIRContext *getContext() const { return context; }
438
439private:
440 mlir::MLIRContext *context;
441};
442
443/// Manages a collection of rewriting patterns for combinational logic
444/// optimization.
445///
446/// This class organizes and provides efficient access to rewriting patterns
447/// used during cut-based optimization. It maintains:
448/// - A collection of all available patterns
449/// - Fast lookup tables for truth table-based matching
450/// - Separation of truth table vs. custom matching patterns
451///
452/// The pattern set is used by the CutRewriter to find suitable replacements
453/// for cuts in the combinational logic network.
455public:
456 /// Constructor that takes ownership of the provided patterns.
457 ///
458 /// During construction, patterns are analyzed and organized for efficient
459 /// lookup. Truth table matchers are indexed by their NPN canonical forms.
461 llvm::SmallVector<std::unique_ptr<CutRewritePattern>, 4> patterns);
462
463private:
464 /// Owned collection of all rewriting patterns.
465 llvm::SmallVector<std::unique_ptr<CutRewritePattern>, 4> patterns;
466
467 /// Fast lookup table mapping NPN canonical forms to matching patterns.
468 /// Each entry maps a truth table and input size to patterns that can handle
469 /// it.
470 DenseMap<std::pair<APInt, unsigned>,
471 SmallVector<std::pair<NPNClass, const CutRewritePattern *>>>
473
474 /// Patterns that use custom matching logic instead of NPN lookup.
475 /// These patterns are checked against every cut.
476 SmallVector<const CutRewritePattern *, 4> nonNPNPatterns;
477
478 /// CutRewriter needs access to internal data structures for pattern matching.
479 friend class CutRewriter;
480};
481
482/// Main cut-based rewriting algorithm for combinational logic optimization.
483///
484/// The CutRewriter implements a cut-based rewriting algorithm that:
485/// 1. Enumerates cuts in the combinational logic network using a priority cuts
486/// algorithm
487/// 2. Matches cuts against available rewriting patterns
488/// 3. Selects optimal patterns based on area or timing objectives
489/// 4. Rewrites the circuit using the selected patterns
490///
491/// The algorithm processes the network in topological order, building up cut
492/// sets for each node and selecting the best implementation based on the
493/// specified optimization strategy.
494///
495/// Usage example:
496/// ```cpp
497/// CutRewriterOptions options;
498/// options.strategy = OptimizationStrategy::Area;
499/// options.maxCutInputSize = 4;
500/// options.maxCutSizePerRoot = 8;
501///
502/// CutRewritePatternSet patterns(std::move(optimizationPatterns));
503/// CutRewriter rewriter(module, options, patterns);
504///
505/// if (failed(rewriter.run())) {
506/// // Handle rewriting failure
507/// }
508/// ```
510public:
511 /// Constructor for the cut rewriter.
514
515 /// Execute the complete cut-based rewriting algorithm.
516 ///
517 /// This method orchestrates the entire rewriting process:
518 /// 1. Enumerate cuts for all nodes in the combinational logic
519 /// 2. Match cuts against available patterns
520 /// 3. Select optimal patterns based on strategy
521 /// 4. Rewrite the circuit with selected patterns
522 LogicalResult run(Operation *topOp);
523
524private:
525 /// Enumerate cuts for all nodes in the given module.
526 /// Note: This preserves module boundaries and does not perform
527 /// rewriting across the hierarchy.
528 LogicalResult enumerateCuts(Operation *topOp);
529
530 /// Find patterns that match a cut's truth table.
531 ArrayRef<std::pair<NPNClass, const CutRewritePattern *>>
532 getMatchingPatternsFromTruthTable(const Cut &cut) const;
533
534 /// Match a cut against available patterns and compute arrival time.
535 std::optional<MatchedPattern> patternMatchCut(const Cut &cut);
536
537 /// Perform the actual circuit rewriting using selected patterns.
538 LogicalResult runBottomUpRewrite(Operation *topOp);
539
540 /// Configuration options
542
543 /// Available rewriting patterns
545
547};
548
549} // namespace synth
550} // namespace circt
551
552#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.
LogicalResult getInputArrivalTimes(CutEnumerator &enumerator, SmallVectorImpl< DelayType > &results) const
Get arrival times for each input 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 TruthTable.h:39
Represents the canonical form of a boolean function under NPN equivalence.
Definition TruthTable.h:104
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