CIRCT 24.0.0git
Loading...
Searching...
No Matches
DatapathToComb.cpp
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
14#include "mlir/Analysis/TopologicalSortUtils.h"
15#include "mlir/Dialect/Func/IR/FuncOps.h"
16#include "mlir/IR/PatternMatch.h"
17#include "mlir/Pass/Pass.h"
18#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
19#include "llvm/Support/Debug.h"
20#include "llvm/Support/KnownBits.h"
21#include <algorithm>
22
23#define DEBUG_TYPE "datapath-to-comb"
24
25namespace circt {
26#define GEN_PASS_DEF_CONVERTDATAPATHTOCOMB
27#include "circt/Conversion/Passes.h.inc"
28} // namespace circt
29
30using namespace circt;
31using namespace datapath;
32
33// A wrapper for comb::extractBits that returns a SmallVector<Value>.
34static SmallVector<Value> extractBits(OpBuilder &builder, Value val) {
35 SmallVector<Value> bits;
36 comb::extractBits(builder, val, bits);
37 return bits;
38}
39
40// Check whether a value is zero-extended or sign-extended - and return the
41// unextended base value and whether it was sign-extended.
42static std::pair<bool, Value> getBaseOfExt(PatternRewriter &rewriter,
43 Location loc, Value val) {
44
45 Value replBits;
46 // Check for zext
47 if (matchPattern(val, comb::m_ZextBy(mlir::matchers::m_Any(&replBits)))) {
48 auto baseWidth = val.getType().getIntOrFloatBitWidth() -
49 replBits.getType().getIntOrFloatBitWidth();
50 auto valBase =
51 rewriter.createOrFold<comb::ExtractOp>(loc, val, 0, baseWidth);
52 return {false, valBase};
53 }
54
55 // Check for sext of the value
56 if (matchPattern(val, comb::m_SextBy(mlir::matchers::m_Any(&replBits)))) {
57 auto baseWidth = val.getType().getIntOrFloatBitWidth() -
58 replBits.getType().getIntOrFloatBitWidth();
59 auto valBase =
60 rewriter.createOrFold<comb::ExtractOp>(loc, val, 0, baseWidth);
61 return {true, valBase};
62 }
63
64 // Not extended, return original value
65 return {false, val};
66}
67
68//===----------------------------------------------------------------------===//
69// Conversion patterns
70//===----------------------------------------------------------------------===//
71
72namespace {
73// Replace compressor by an adder of the inputs and zero for the other results:
74// compress(a,b,c,d) -> {a+b+c+d, 0}
75// Facilitates use of downstream compression algorithms e.g. Yosys
76struct DatapathCompressOpAddConversion : mlir::OpRewritePattern<CompressOp> {
78 LogicalResult
79 matchAndRewrite(CompressOp op,
80 mlir::PatternRewriter &rewriter) const override {
81 Location loc = op.getLoc();
82 auto inputs = op.getOperands();
83 unsigned width = inputs[0].getType().getIntOrFloatBitWidth();
84 // Sum all the inputs - set that to result value 0
85 auto addOp = comb::AddOp::create(rewriter, loc, inputs, true);
86 // Replace remaining results with zeros
87 auto zeroOp = hw::ConstantOp::create(rewriter, loc, APInt(width, 0));
88 SmallVector<Value> results(op.getNumResults() - 1, zeroOp);
89 results.push_back(addOp);
90 rewriter.replaceOp(op, results);
91 return success();
92 }
93};
94
95// Replace compressor by a wallace tree of full-adders
96struct DatapathCompressOpConversion : mlir::OpRewritePattern<CompressOp> {
97 DatapathCompressOpConversion(MLIRContext *context,
99 : mlir::OpRewritePattern<CompressOp>(context), analysis(analysis) {}
100
101 LogicalResult
102 matchAndRewrite(CompressOp op,
103 mlir::PatternRewriter &rewriter) const override {
104 Location loc = op.getLoc();
105 auto inputs = op.getOperands();
106
107 SmallVector<SmallVector<Value>> addends;
108 for (auto input : inputs) {
109 addends.push_back(
110 extractBits(rewriter, input)); // Extract bits from each input
111 }
112
113 // Compressor tree reduction
114 auto width = inputs[0].getType().getIntOrFloatBitWidth();
115 auto targetAddends = op.getNumResults();
116 datapath::CompressorTree comp(width, addends, loc, rewriter);
117
118 if (analysis) {
119 // Update delay information with arrival times
120 if (failed(comp.withInputDelays(
121 [&](Value v) { return analysis->getMaxDelay(v, 0); })))
122 return failure();
123 }
124
125 rewriter.replaceOp(op, comp.compressToHeight(rewriter, targetAddends));
126 return success();
127 }
128
129private:
130 synth::IncrementalLongestPathAnalysis *analysis = nullptr;
131};
132
133struct DatapathPartialProductOpConversion : OpRewritePattern<PartialProductOp> {
134 using OpRewritePattern<PartialProductOp>::OpRewritePattern;
135
136 DatapathPartialProductOpConversion(MLIRContext *context, bool forceBooth)
137 : OpRewritePattern<PartialProductOp>(context), forceBooth(forceBooth){};
138
139 const bool forceBooth;
140
141 LogicalResult matchAndRewrite(PartialProductOp op,
142 PatternRewriter &rewriter) const override {
143
144 Value a = op.getLhs();
145 Value b = op.getRhs();
146 unsigned width = a.getType().getIntOrFloatBitWidth();
147
148 // Skip a zero width value.
149 if (width == 0) {
150 rewriter.replaceOpWithNewOp<hw::ConstantOp>(op, op.getType(0), 0);
151 return success();
152 }
153
154 // Square partial product array can be reduced to upper triangular array.
155 // For example: AND array for a 4-bit squarer:
156 // 0 0 0 a0a3 a0a2 a0a1 a0a0
157 // 0 0 a1a3 a1a2 a1a1 a1a0 0
158 // 0 a2a3 a2a2 a2a1 a2a0 0 0
159 // a3a3 a3a2 a3a1 a3a0 0 0 0
160 //
161 // Can be reduced to:
162 // 0 0 a0a3 a0a2 a0a1 0 a0
163 // 0 a1a3 a1a2 0 a1 0 0
164 // a2a3 0 a2 0 0 0 0
165 // a3 0 0 0 0 0 0
166 if (a == b)
167 return lowerSqrAndArray(rewriter, a, op, width);
168
169 // Use result rows as a heuristic to guide partial product
170 // implementation
171 if (comb::shouldUseBoothEncoding(a, b) || forceBooth)
172 return lowerBoothArray(rewriter, a, b, op, width);
173 else
174 return lowerAndArray(rewriter, a, b, op, width);
175 }
176
177private:
178 static LogicalResult lowerAndArray(PatternRewriter &rewriter, Value a,
179 Value b, PartialProductOp op,
180 unsigned width) {
181
182 Location loc = op.getLoc();
183 // Keep a as a bitvector - multiply by each digit of b
184 SmallVector<Value> bBits = extractBits(rewriter, b);
185 auto knownBitsB = comb::computeKnownBits(b);
186
187 auto rowWidth = width;
188 auto knownBitsA = comb::computeKnownBits(a);
189 if (!knownBitsA.Zero.isZero()) {
190 if (knownBitsA.Zero.countLeadingOnes() > 1) {
191 rowWidth -= knownBitsA.Zero.countLeadingOnes();
192 a = rewriter.createOrFold<comb::ExtractOp>(loc, a, 0, rowWidth);
193 }
194 }
195
196 SmallVector<Value> partialProducts;
197 partialProducts.reserve(width);
198 // AND Array Construction:
199 // partialProducts[i] = ({b[i],..., b[i]} & a) << i
200 assert(op.getNumResults() <= width &&
201 "Cannot return more results than the operator width");
202
203 for (unsigned i = 0; i < op.getNumResults(); ++i) {
204 // Constuct partial product row for bit i of b.
205 Value ppRow;
206
207 // Skip generation of zero rows.
208 if (knownBitsB.Zero[i]) {
209 partialProducts.push_back(
210 hw::ConstantOp::create(rewriter, loc, APInt(width, 0)));
211 continue;
212 }
213
214 // If the bit is known to be one, just use `a` as the partial product row.
215 if (knownBitsB.One[i]) {
216 ppRow = a;
217 } else {
218 auto repl =
219 rewriter.createOrFold<comb::ReplicateOp>(loc, bBits[i], rowWidth);
220 ppRow = rewriter.createOrFold<comb::AndOp>(loc, repl, a);
221 }
222 if (rowWidth < width) {
223 auto padding = width - rowWidth;
224 auto zeroPad = hw::ConstantOp::create(rewriter, loc, APInt(padding, 0));
225 ppRow = rewriter.createOrFold<comb::ConcatOp>(
226 loc, ValueRange{zeroPad, ppRow}); // Pad to full width
227 }
228
229 if (i == 0) {
230 partialProducts.push_back(ppRow);
231 continue;
232 }
233 auto shiftBy = hw::ConstantOp::create(rewriter, loc, APInt(i, 0));
234 auto ppAlign =
235 comb::ConcatOp::create(rewriter, loc, ValueRange{ppRow, shiftBy});
236 auto ppAlignTrunc = rewriter.createOrFold<comb::ExtractOp>(
237 loc, ppAlign, 0, width); // Truncate to width+i bits
238 partialProducts.push_back(ppAlignTrunc);
239 }
240
241 rewriter.replaceOp(op, partialProducts);
242 return success();
243 }
244
245 static LogicalResult lowerSqrAndArray(PatternRewriter &rewriter, Value a,
246 PartialProductOp op, unsigned width) {
247
248 Location loc = op.getLoc();
249 SmallVector<Value> aBits = extractBits(rewriter, a);
250
251 SmallVector<Value> partialProducts;
252 partialProducts.reserve(width);
253 // AND Array Construction - reducing to upper triangle:
254 // partialProducts[i] = ({a[i],..., a[i]} & a) << i
255 // optimised to: {a[i] & a[n-1], ..., a[i] & a[i+1], 0, a[i], 0, ..., 0}
256 assert(op.getNumResults() <= width &&
257 "Cannot return more results than the operator width");
258 auto zeroFalse = hw::ConstantOp::create(rewriter, loc, APInt(1, 0));
259 for (unsigned i = 0; i < op.getNumResults(); ++i) {
260 SmallVector<Value> row;
261 row.reserve(width);
262
263 if (2 * i >= width) {
264 // Pad the remaining rows with zeros
265 auto zeroWidth = hw::ConstantOp::create(rewriter, loc, APInt(width, 0));
266 partialProducts.push_back(zeroWidth);
267 continue;
268 }
269
270 if (i > 0) {
271 auto shiftBy = hw::ConstantOp::create(rewriter, loc, APInt(2 * i, 0));
272 row.push_back(shiftBy);
273 }
274 row.push_back(aBits[i]);
275
276 // Track width of constructed row
277 unsigned rowWidth = 2 * i + 1;
278 if (rowWidth < width) {
279 row.push_back(zeroFalse);
280 ++rowWidth;
281 }
282
283 for (unsigned j = i + 1; j < width; ++j) {
284 // Stop when we reach the required width
285 if (rowWidth == width)
286 break;
287
288 // Otherwise pad with zeros or partial product bits
289 ++rowWidth;
290 // Number of results indicates number of non-zero bits in input
291 if (j >= op.getNumResults()) {
292 row.push_back(zeroFalse);
293 continue;
294 }
295
296 auto ppBit =
297 rewriter.createOrFold<comb::AndOp>(loc, aBits[i], aBits[j]);
298 row.push_back(ppBit);
299 }
300 std::reverse(row.begin(), row.end());
301 auto ppRow = comb::ConcatOp::create(rewriter, loc, row);
302 partialProducts.push_back(ppRow);
303 }
304
305 rewriter.replaceOp(op, partialProducts);
306 return success();
307 }
308
309 static LogicalResult lowerBoothArray(PatternRewriter &rewriter, Value a,
310 Value b, PartialProductOp op,
311 unsigned width) {
312 // TODO: sort a and b based on non-zero bits to encode the smaller input
313 Location loc = op.getLoc();
314 auto zeroFalse = hw::ConstantOp::create(rewriter, loc, APInt(1, 0));
315
316 auto [aSigned, aBase] = getBaseOfExt(rewriter, loc, op.getLhs());
317 auto [bSigned, bBase] = getBaseOfExt(rewriter, loc, op.getRhs());
318
319 auto aBaseWidth = aBase.getType().getIntOrFloatBitWidth();
320 auto bBaseWidth = bBase.getType().getIntOrFloatBitWidth();
321
322 // Detect leading zeros in multiplicand due to zero-extension
323 // and truncate to reduce partial product bits {'0, a} * {'0, b}
324 auto rowWidth = width;
325 if (aBaseWidth < width) {
326 // Retain one leading zero/sign-bit to represent 2*a
327 rowWidth = aBaseWidth + 1;
328 a = rewriter.createOrFold<comb::ExtractOp>(loc, a, 0, rowWidth);
329 }
330
331 // Booth encoding will select each row from {-2a, -1a, 0, 1a, 2a}
332 Value twoAPre =
333 rewriter.createOrFold<comb::ConcatOp>(loc, ValueRange{a, zeroFalse});
334 Value twoA = rewriter.createOrFold<comb::ExtractOp>(
335 loc, twoAPre, 0, rowWidth); // Truncate to width bits
336
337 // Encode based on the bits of b
338
339 SmallVector<Value> bBits = extractBits(rewriter, b);
340 // Pad with two zeros - for case where there's no extensions
341 bBits.push_back(zeroFalse); // Add a zero bit for the first row
342 bBits.push_back(zeroFalse); // Add a zero bit for the last row
343
344 // Retain two leading zeros as when b has an even number of bits we just
345 // need to retain two leading zeros
346 if (!bSigned)
347 bBits.resize(bBaseWidth + 2);
348
349 // If b is signed, we need to sign-extend with a single sign-bit
350 if (bSigned)
351 bBits.resize(bBaseWidth + 1);
352
353 SmallVector<Value> partialProducts;
354 partialProducts.reserve(op.getNumResults());
355
356 // Booth encoding halves array height by grouping three bits at a time:
357 // partialProducts[i] = a * (-2*b[2*i+1] + b[2*i] + b[2*i-1]) << 2*i
358 // encNeg \approx (-2*b[2*i+1] + b[2*i] + b[2*i-1]) <= 0
359 // encOne = (-2*b[2*i+1] + b[2*i] + b[2*i-1]) == +/- 1
360 // encTwo = (-2*b[2*i+1] + b[2*i] + b[2*i-1]) == +/- 2
361 SmallVector<Value> encNegs;
362 Value encNegPrev;
363
364 // For even width - additional row contains the final sign correction
365 for (unsigned i = 0; i + 1 < bBits.size(); i += 2) {
366 // Get Booth bits: b[i+1], b[i], b[i-1] (b[-1] = 0)
367 Value bim1 = (i == 0) ? zeroFalse : bBits[i - 1];
368 Value bi = bBits[i];
369 Value bip1 = bBits[i + 1];
370
371 // Is the encoding zero or negative (an approximation)
372 Value encNeg = bip1;
373 encNegs.push_back(encNeg); // Store for sign-extension optimisation
374 // Is the encoding one = b[i] xor b[i-1]
375 Value encOne = rewriter.createOrFold<comb::XorOp>(loc, bi, bim1, true);
376 // Is the encoding two = (bip1 & ~bi & ~bim1) | (~bip1 & bi & bim1)
377 Value constOne = hw::ConstantOp::create(rewriter, loc, APInt(1, 1));
378 Value biInv = rewriter.createOrFold<comb::XorOp>(loc, bi, constOne, true);
379 Value bip1Inv =
380 rewriter.createOrFold<comb::XorOp>(loc, bip1, constOne, true);
381 Value bim1Inv =
382 rewriter.createOrFold<comb::XorOp>(loc, bim1, constOne, true);
383
384 Value andLeft = rewriter.createOrFold<comb::AndOp>(
385 loc, ValueRange{bip1Inv, bi, bim1}, true);
386 Value andRight = rewriter.createOrFold<comb::AndOp>(
387 loc, ValueRange{bip1, biInv, bim1Inv}, true);
388 Value encTwo =
389 rewriter.createOrFold<comb::OrOp>(loc, andLeft, andRight, true);
390
391 Value encNegRepl =
392 rewriter.createOrFold<comb::ReplicateOp>(loc, encNeg, rowWidth);
393 Value encOneRepl =
394 rewriter.createOrFold<comb::ReplicateOp>(loc, encOne, rowWidth);
395 Value encTwoRepl =
396 rewriter.createOrFold<comb::ReplicateOp>(loc, encTwo, rowWidth);
397
398 // Select between 2*a or 1*a or 0*a
399 Value selTwoA = rewriter.createOrFold<comb::AndOp>(loc, encTwoRepl, twoA);
400 Value selOneA = rewriter.createOrFold<comb::AndOp>(loc, encOneRepl, a);
401 Value magA =
402 rewriter.createOrFold<comb::OrOp>(loc, selTwoA, selOneA, true);
403
404 // Conditionally invert the row
405 Value ppRow =
406 rewriter.createOrFold<comb::XorOp>(loc, magA, encNegRepl, true);
407
408 // No sign-correction in the first row
409 if (i == 0) {
410 partialProducts.push_back(ppRow);
411 encNegPrev = encNeg;
412 continue;
413 }
414
415 if (i == 2) {
416 Value withSignCorrection = rewriter.createOrFold<comb::ConcatOp>(
417 loc, ValueRange{ppRow, zeroFalse, encNegPrev});
418 partialProducts.push_back(withSignCorrection);
419 encNegPrev = encNeg;
420 continue;
421 }
422
423 // Insert a sign-correction from the previous row
424 // {ppRow, 0, encNegPrev} << (i-2)
425 Value shiftBy = hw::ConstantOp::create(rewriter, loc, APInt(i - 2, 0));
426 Value withSignCorrection = rewriter.createOrFold<comb::ConcatOp>(
427 loc, ValueRange{ppRow, zeroFalse, encNegPrev, shiftBy});
428 partialProducts.push_back(withSignCorrection);
429 encNegPrev = encNeg;
430
431 if (partialProducts.size() == op.getNumResults())
432 break;
433 }
434
435 // Add the final sign-correction row for signed multiplication
436 // Not necessary for unsigned multiplication as the final row is positive
437 if (bSigned) {
438 auto numPP = partialProducts.size();
439 Value shiftByFinal =
440 hw::ConstantOp::create(rewriter, loc, APInt((numPP - 1) * 2, 0));
441 Value finalSignCorrection = rewriter.createOrFold<comb::ConcatOp>(
442 loc, ValueRange{zeroFalse, encNegPrev, shiftByFinal});
443 partialProducts.push_back(finalSignCorrection);
444 encNegs.push_back(zeroFalse); // No sign-extension for the final row
445 }
446
447 // Sign-extension:
448 // { s1, s1, s1, s1, s1, p1}
449 // { s2, s2, s2, p2 }
450 // { s3, p3 }
451 // TODO: optimize by only replicating the sign bit once using
452 // typical sign-extension trick - can be handled by separate
453 // canonicalization patterns
454 for (unsigned i = 0; i < partialProducts.size(); ++i) {
455 auto ppRow = partialProducts[i];
456
457 auto ppWidth = ppRow.getType().getIntOrFloatBitWidth();
458 if (ppWidth < width) {
459 auto padding = width - ppWidth;
460 auto encNeg = encNegs[i];
461 if (aSigned)
462 encNeg = rewriter.createOrFold<comb::ExtractOp>(loc, ppRow,
463 ppWidth - 1, 1);
464
465 // Replicate the encNeg bit for sign-extension
466 Value encNegPad =
467 rewriter.createOrFold<comb::ReplicateOp>(loc, encNeg, padding);
468 ppRow = rewriter.createOrFold<comb::ConcatOp>(
469 loc, ValueRange{encNegPad, ppRow}); // Pad to full width
470 }
471
472 // Truncate any excess bits
473 ppWidth = ppRow.getType().getIntOrFloatBitWidth();
474 if (ppWidth > width) {
475 ppRow = rewriter.createOrFold<comb::ExtractOp>(loc, ppRow, 0, width);
476 }
477 partialProducts[i] = ppRow;
478 assert(partialProducts[i].getType().getIntOrFloatBitWidth() == width &&
479 "Expected sign-extended partial product to be full width");
480 }
481
482 // Zero-pad to match the required output width
483 auto zeroWidth = hw::ConstantOp::create(rewriter, loc, APInt(width, 0));
484 while (partialProducts.size() < op.getNumResults())
485 partialProducts.push_back(zeroWidth);
486
487 assert(partialProducts.size() == op.getNumResults() &&
488 "Expected number of booth partial products to match results");
489
490 rewriter.replaceOp(op, partialProducts);
491 return success();
492 }
493};
494
495struct DatapathPosPartialProductOpConversion
496 : OpRewritePattern<PosPartialProductOp> {
497 using OpRewritePattern<PosPartialProductOp>::OpRewritePattern;
498
499 DatapathPosPartialProductOpConversion(MLIRContext *context, bool forceBooth)
500 : OpRewritePattern<PosPartialProductOp>(context),
501 forceBooth(forceBooth){};
502
503 const bool forceBooth;
504
505 LogicalResult matchAndRewrite(PosPartialProductOp op,
506 PatternRewriter &rewriter) const override {
507
508 Value a = op.getAddend0();
509 Value b = op.getAddend1();
510 Value c = op.getMultiplicand();
511 unsigned width = a.getType().getIntOrFloatBitWidth();
512
513 // Skip a zero width value.
514 if (width == 0) {
515 rewriter.replaceOpWithNewOp<hw::ConstantOp>(op, op.getType(0), 0);
516 return success();
517 }
518
519 // TODO: Implement Booth lowering
520 return lowerAndArray(rewriter, a, b, c, op, width);
521 }
522
523private:
524 static LogicalResult lowerAndArray(PatternRewriter &rewriter, Value a,
525 Value b, Value c, PosPartialProductOp op,
526 unsigned width) {
527
528 Location loc = op.getLoc();
529 // Encode (a+b) by implementing a half-adder - then note the following
530 // fact carry[i] & save[i] == false
531 auto carry = rewriter.createOrFold<comb::AndOp>(loc, a, b);
532 auto save = rewriter.createOrFold<comb::XorOp>(loc, a, b);
533
534 SmallVector<Value> carryBits = extractBits(rewriter, carry);
535 SmallVector<Value> saveBits = extractBits(rewriter, save);
536
537 // Reduce c width based on leading zeros
538 auto rowWidth = width;
539 auto [cSigned, cBase] = getBaseOfExt(rewriter, loc, c);
540 auto cBaseWidth = cBase.getType().getIntOrFloatBitWidth();
541
542 if (cBaseWidth < width && !cSigned) {
543 // Retain one leading zero to represent 2*c
544 rowWidth = cBaseWidth + 1;
545 c = rewriter.createOrFold<comb::ExtractOp>(loc, c, 0, rowWidth);
546 }
547
548 // Compute 2*c for use in array construction
549 Value zeroFalse = hw::ConstantOp::create(rewriter, loc, APInt(1, 0));
550 Value twoCPre =
551 comb::ConcatOp::create(rewriter, loc, ValueRange{c, zeroFalse});
552 Value twoC = rewriter.createOrFold<comb::ExtractOp>(loc, twoCPre, 0,
553 rowWidth); // Truncate
554
555 // AND Array Construction:
556 // pp[i] = ( (carry[i] * (c<<1)) | (save[i] * c) ) << i
557 SmallVector<Value> partialProducts;
558 partialProducts.reserve(width);
559
560 assert(op.getNumResults() <= width &&
561 "Cannot return more results than the operator width");
562
563 for (unsigned i = 0; i < op.getNumResults(); ++i) {
564 auto replSave =
565 rewriter.createOrFold<comb::ReplicateOp>(loc, saveBits[i], rowWidth);
566 auto replCarry =
567 rewriter.createOrFold<comb::ReplicateOp>(loc, carryBits[i], rowWidth);
568
569 auto ppRowSave = rewriter.createOrFold<comb::AndOp>(loc, replSave, c);
570 auto ppRowCarry =
571 rewriter.createOrFold<comb::AndOp>(loc, replCarry, twoC);
572 auto ppRow =
573 rewriter.createOrFold<comb::OrOp>(loc, ppRowSave, ppRowCarry);
574 auto ppAlign = ppRow;
575 if (i > 0) {
576 auto shiftBy = hw::ConstantOp::create(rewriter, loc, APInt(i, 0));
577 ppAlign =
578 comb::ConcatOp::create(rewriter, loc, ValueRange{ppRow, shiftBy});
579 }
580
581 // May need to truncate shifted value
582 if (rowWidth + i > width) {
583 auto ppAlignTrunc =
584 rewriter.createOrFold<comb::ExtractOp>(loc, ppAlign, 0, width);
585 partialProducts.push_back(ppAlignTrunc);
586 continue;
587 }
588 // May need to zero pad to approriate width
589 if (rowWidth + i < width) {
590 auto extPPAlign = comb::createZExt(rewriter, loc, ppAlign, width);
591 partialProducts.push_back(extPPAlign);
592 continue;
593 }
594
595 partialProducts.push_back(ppAlign);
596 }
597
598 rewriter.replaceOp(op, partialProducts);
599 return success();
600 }
601};
602
603} // namespace
604
605//===----------------------------------------------------------------------===//
606// Convert Datapath to Comb pass
607//===----------------------------------------------------------------------===//
608
609namespace {
610struct ConvertDatapathToCombPass
611 : public impl::ConvertDatapathToCombBase<ConvertDatapathToCombPass> {
612 void runOnOperation() override;
613 using ConvertDatapathToCombBase<
614 ConvertDatapathToCombPass>::ConvertDatapathToCombBase;
615};
616} // namespace
617
619 Operation *op, RewritePatternSet &&patterns,
621 // TODO: Topologically sort the operations in the module to ensure that all
622 // dependencies are processed before their users.
623 mlir::GreedyRewriteConfig config;
624 // Set the listener to update timing information
625 // HACK: Setting max iterations to 2 to ensure that the patterns are
626 // one-shot, making sure target operations are datapath operations are
627 // replaced.
628 config.setMaxIterations(2).setListener(analysis).setUseTopDownTraversal(true);
629
630 // Apply the patterns greedily
631 if (failed(mlir::applyPatternsGreedily(op, std::move(patterns), config)))
632 return failure();
633
634 return success();
635}
636
637void ConvertDatapathToCombPass::runOnOperation() {
638 RewritePatternSet patterns(&getContext());
639
640 patterns.add<DatapathPartialProductOpConversion,
641 DatapathPosPartialProductOpConversion>(patterns.getContext(),
642 forceBooth);
643 synth::IncrementalLongestPathAnalysis *analysis = nullptr;
644 if (timingAware)
645 analysis = &getAnalysis<synth::IncrementalLongestPathAnalysis>();
646
647 if (lowerCompressToAdd)
648 // Lower compressors to simple add operations for downstream optimisations
649 patterns.add<DatapathCompressOpAddConversion>(patterns.getContext());
650 if (lowerCompress)
651 // Lower compressors to a complete gate-level implementation
652 patterns.add<DatapathCompressOpConversion>(patterns.getContext(), analysis);
653
655 getOperation(), std::move(patterns), analysis)))
656 return signalPassFailure();
657
658 // Verify that all Datapath operations have been successfully converted.
659 // Walk the operation and check for any remaining Datapath dialect
660 // operations.
661 auto result = getOperation()->walk([&](Operation *op) {
662 if (llvm::isa<datapath::CompressOp>(op) && !lowerCompress &&
663 !lowerCompressToAdd)
664 return WalkResult::advance();
665 if (llvm::isa_and_nonnull<datapath::DatapathDialect>(op->getDialect())) {
666 op->emitError("Datapath operation not converted: ") << *op;
667 return WalkResult::interrupt();
668 }
669 return WalkResult::advance();
670 });
671 if (result.wasInterrupted())
672 return signalPassFailure();
673}
assert(baseType &&"element must be base type")
static SmallVector< Value > extractBits(OpBuilder &builder, Value val)
static Value zeroPad(PatternRewriter &rewriter, Location loc, Value input, size_t targetWidth, size_t trailingZeros)
static std::pair< bool, Value > getBaseOfExt(PatternRewriter &rewriter, Location loc, Value val)
static SmallVector< Value > extractBits(OpBuilder &builder, Value val)
static LogicalResult applyPatternsGreedilyWithTimingInfo(Operation *op, RewritePatternSet &&patterns, synth::IncrementalLongestPathAnalysis *analysis)
static std::unique_ptr< Context > context
create(data_type, value)
Definition hw.py:433
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.