CIRCT 24.0.0git
Loading...
Searching...
No Matches
Mem2Reg.cpp
Go to the documentation of this file.
1//===- Mem2Reg.cpp - Promote signal/memory slots to values ----------------===//
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#include "CaptureUtils.h"
10#include "ProjectionUtils.h"
16#include "mlir/Analysis/Liveness.h"
17#include "mlir/Dialect/Arith/IR/Arith.h"
18#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
19#include "mlir/IR/Dominance.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/Support/Debug.h"
22
23#define DEBUG_TYPE "llhd-mem2reg"
24
25namespace circt {
26namespace llhd {
27#define GEN_PASS_DEF_MEM2REGPASS
28#include "circt/Dialect/LLHD/LLHDPasses.h.inc"
29} // namespace llhd
30} // namespace circt
31
32using namespace mlir;
33using namespace circt;
34using namespace llhd;
35using llvm::ArrayRef;
36using llvm::PointerIntPair;
37using llvm::SmallDenseSet;
39using llvm::SpecificBumpPtrAllocator;
40
41/// Check whether an operation is an `llhd.assign`. This corresponds to a
42/// blocking assignment in Verilog.
43static bool isBlockingDrive(const Operation *op) { return isa<AssignOp>(op); }
44
45/// Check whether an operation is a `llhd.drv` with a delta delay. This
46/// corresponds to a non-blocking assignment in Verilog.
47static bool isDeltaDrive(const Operation *op) {
48 if (auto driveOp = dyn_cast<DriveOp>(op)) {
49 if (auto timeOp = driveOp.getTime().getDefiningOp<ConstantTimeOp>()) {
50 auto t = timeOp.getValue();
51 return t.getTime() == 0 && t.getDelta() == 1;
52 }
53 }
54 return false;
55}
56
57//===----------------------------------------------------------------------===//
58// Reaching Definitions and Placeholders
59//===----------------------------------------------------------------------===//
60
61namespace {
62/// Information about whether a definition is driven back onto its signal. For
63/// example, probes provide a definition for their signal that does not have to
64/// be driven back onto the signal. Drives on the other hand provide a
65/// definition that eventually must be driven onto the signal.
66struct DriveCondition {
67 static DriveCondition never() { return ConditionAndMode(Value{}, Never); }
68 static DriveCondition always() { return ConditionAndMode(Value{}, Always); }
69 static DriveCondition conditional(Value condition = {}) {
70 return ConditionAndMode(condition, Conditional);
71 }
72
73 bool isNever() const { return conditionAndMode.getInt() == Never; }
74 bool isAlways() const { return conditionAndMode.getInt() == Always; }
75 bool isConditional() const {
76 return conditionAndMode.getInt() == Conditional;
77 }
78
79 Value getCondition() const { return conditionAndMode.getPointer(); }
80 void setCondition(Value condition) { conditionAndMode.setPointer(condition); }
81
82 bool operator==(const DriveCondition &other) const {
83 return conditionAndMode == other.conditionAndMode;
84 }
85 bool operator!=(const DriveCondition &other) const {
86 return conditionAndMode != other.conditionAndMode;
87 }
88
89private:
90 enum {
91 Never,
92 Always,
93 Conditional,
94 };
95 typedef PointerIntPair<Value, 2> ConditionAndMode;
96 ConditionAndMode conditionAndMode;
97
98 DriveCondition(ConditionAndMode conditionAndMode)
99 : conditionAndMode(conditionAndMode) {}
100 friend DenseMapInfo<DriveCondition>;
101};
102
103/// A definition for a memory slot that may not yet have a concrete SSA value.
104/// These are created for blocks which need to merge distinct definitions for
105/// the same slot coming from its predecssors, as a standin before block
106/// arguments are created. They are also created for drives, where a concrete
107/// value is already available in the form of the driven value.
108struct Def {
109 Block *block;
110 Type type;
111 Value value;
112 DriveCondition condition;
113 bool valueIsPlaceholder = false;
114 bool conditionIsPlaceholder = false;
115
116 Def(Value value, DriveCondition condition)
117 : block(value.getParentBlock()), type(value.getType()), value(value),
118 condition(condition) {}
119 Def(Block *block, Type type, DriveCondition condition)
120 : block(block), type(type), condition(condition) {}
121
122 Value getValueOrPlaceholder();
123 Value getConditionOrPlaceholder();
124};
125} // namespace
126
127/// Return the SSA value for this definition if it already has one, or create
128/// a placeholder value if no value exists yet.
129Value Def::getValueOrPlaceholder() {
130 if (!value) {
131 auto builder = OpBuilder::atBlockBegin(block);
132 value = UnrealizedConversionCastOp::create(builder, builder.getUnknownLoc(),
133 type, ValueRange{})
134 .getResult(0);
135 valueIsPlaceholder = true;
136 }
137 return value;
138}
139
140/// Return the drive condition for this definition. Creates a constant false or
141/// true SSA value if the drive mode is "never" or "always", respectively. If
142/// the mode is "conditional", return the its condition value if it already has
143/// one, or create a placeholder value if no value exists yet.
144Value Def::getConditionOrPlaceholder() {
145 if (!condition.getCondition()) {
146 auto builder = OpBuilder::atBlockBegin(block);
147 Value value;
148 if (condition.isNever()) {
149 value = hw::ConstantOp::create(builder, builder.getUnknownLoc(),
150 builder.getI1Type(), 0);
151 } else if (condition.isAlways()) {
152 value = hw::ConstantOp::create(builder, builder.getUnknownLoc(),
153 builder.getI1Type(), 1);
154 } else {
155 value =
156 UnrealizedConversionCastOp::create(builder, builder.getUnknownLoc(),
157 builder.getI1Type(), ValueRange{})
158 .getResult(0);
159 conditionIsPlaceholder = true;
160 }
161 condition.setCondition(value);
162 }
163 return condition.getCondition();
164}
165
166// Allow `DriveCondition` to be used as hash map key.
167template <>
168struct llvm::DenseMapInfo<DriveCondition> {
169 static unsigned getHashValue(DriveCondition d) {
171 d.conditionAndMode);
172 }
173 static bool isEqual(DriveCondition lhs, DriveCondition rhs) {
174 return lhs == rhs;
175 }
176};
177
178//===----------------------------------------------------------------------===//
179// Lattice to Propagate Needed and Reaching Definitions
180//===----------------------------------------------------------------------===//
181
182/// The slot a reaching definition specifies a value for, alongside a bit
183/// indicating whether the definition is from a delayed drive or a blocking
184/// drive.
185using DefSlot = PointerIntPair<Value, 1>;
186static DefSlot blockingSlot(Value slot) { return {slot, 0}; }
187static DefSlot delayedSlot(Value slot) { return {slot, 1}; }
188static Value getSlot(DefSlot slot) { return slot.getPointer(); }
189static bool isDelayed(DefSlot slot) { return slot.getInt(); }
190static Type getStoredType(DefSlot slot) {
191 return getStoredType(slot.getPointer());
192}
193static Location getLoc(DefSlot slot) { return slot.getPointer().getLoc(); }
194
195static std::optional<unsigned> getPromotableSlotBitWidth(Type type) {
196 if (auto intTy = dyn_cast<IntegerType>(type))
197 return intTy.getWidth();
198 if (auto floatTy = dyn_cast<FloatType>(type))
199 return floatTy.getWidth();
200
201 auto bitWidth = hw::getBitWidth(type);
202 if (bitWidth < 0)
203 return std::nullopt;
204 return static_cast<unsigned>(bitWidth);
205}
206
207static bool isPromotableSlotType(Type type) {
208 auto bitWidth = getPromotableSlotBitWidth(type);
209 return bitWidth && *bitWidth <= IntegerType::kMaxWidth;
210}
211
212static Value createZeroValue(OpBuilder &builder, Location loc, Type type) {
213 if (isa<FloatType>(type))
214 return arith::ConstantOp::create(builder, loc, builder.getZeroAttr(type));
215
216 auto bitWidth = getPromotableSlotBitWidth(type);
217 assert(bitWidth && "cannot create zero value for unpromotable slot type");
218 auto flatType = builder.getIntegerType(*bitWidth);
219 Value value = hw::ConstantOp::create(builder, loc, flatType, 0);
220 if (type != flatType)
221 value = hw::BitcastOp::create(builder, loc, type, value);
222 return value;
223}
224
225namespace {
226
227struct LatticeNode;
228struct BlockExit;
229struct ProbeNode;
230struct DriveNode;
231struct SlotNode;
232
233/// Lattice state between two adjacent lattice nodes for a single slot.
234///
235/// `needed` records whether a definition of the slot has to be available at
236/// this program point, computed by the backward pass. The two reaching-def
237/// pointers carry the slot's definitions for the blocking and delayed
238/// flavors, computed by the forward pass; either may be null when the slot
239/// has no definition reaching this point.
240struct LatticeValue {
241 LatticeNode *nodeBefore = nullptr;
242 LatticeNode *nodeAfter = nullptr;
243 bool needed = false;
244 Def *blockingReachingDef = nullptr;
245 Def *delayedReachingDef = nullptr;
246
247 /// Return the reaching def for the blocking/delayed flavor of this slot.
248 Def *getReachingDef(bool delayed) const {
249 return delayed ? delayedReachingDef : blockingReachingDef;
250 }
251 void setReachingDef(bool delayed, Def *def) {
252 (delayed ? delayedReachingDef : blockingReachingDef) = def;
253 }
254};
255
256struct LatticeNode {
257 enum class Kind { BlockEntry, BlockExit, Probe, Drive, Slot };
258 const Kind kind;
259 /// Dirty flag to prevent duplicate pushes to worklist.
260 bool dirty = false;
261 LatticeNode(Kind kind) : kind(kind) {}
262};
263
264struct BlockEntry : public LatticeNode {
265 Block *block;
266 LatticeValue *valueAfter;
267 SmallVector<BlockExit *, 2> predecessors;
268 /// Probe op inserted at the start of this block for the slot being
269 /// promoted, if a definition is needed here but not provided by all
270 /// predecessors.
271 Def *insertedProbe = nullptr;
272 /// Merge definitions created for this block entry when predecessors
273 /// disagree on the reaching def. One per flavor, mirroring `LatticeValue`.
274 Def *blockingMerged = nullptr;
275 Def *delayedMerged = nullptr;
276
277 BlockEntry(Block *block, LatticeValue *valueAfter)
278 : LatticeNode(Kind::BlockEntry), block(block), valueAfter(valueAfter) {
279 assert(!valueAfter->nodeBefore);
280 valueAfter->nodeBefore = this;
281 }
282
283 Def *getMerged(bool delayed) const {
284 return delayed ? delayedMerged : blockingMerged;
285 }
286 void setMerged(bool delayed, Def *def) {
287 (delayed ? delayedMerged : blockingMerged) = def;
288 }
289
290 static bool classof(const LatticeNode *n) {
291 return n->kind == Kind::BlockEntry;
292 }
293};
294
295struct BlockExit : public LatticeNode {
296 Block *block;
297 LatticeValue *valueBefore;
298 SmallVector<BlockEntry *, 2> successors;
299 Operation *terminator;
300 bool suspends;
301
302 BlockExit(Block *block, LatticeValue *valueBefore)
303 : LatticeNode(Kind::BlockExit), block(block), valueBefore(valueBefore),
304 terminator(block->getTerminator()),
305 suspends(isa<HaltOp, WaitOp>(terminator)) {
306 assert(!valueBefore->nodeAfter);
307 valueBefore->nodeAfter = this;
308 }
309
310 static bool classof(const LatticeNode *n) {
311 return n->kind == Kind::BlockExit;
312 }
313};
314
315struct OpNode : public LatticeNode {
316 Operation *op;
317 LatticeValue *valueBefore;
318 LatticeValue *valueAfter;
319
320 OpNode(Kind kind, Operation *op, LatticeValue *valueBefore,
321 LatticeValue *valueAfter)
322 : LatticeNode(kind), op(op), valueBefore(valueBefore),
323 valueAfter(valueAfter) {
324 assert(!valueBefore->nodeAfter);
325 assert(!valueAfter->nodeBefore);
326 valueBefore->nodeAfter = this;
327 valueAfter->nodeBefore = this;
328 }
329
330 static bool classof(const LatticeNode *n) {
331 return isa<ProbeNode, DriveNode, SlotNode>(n);
332 }
333};
334
335struct ProbeNode : public OpNode {
336 Value slot;
337
338 ProbeNode(ProbeOp op, Value slot, LatticeValue *valueBefore,
339 LatticeValue *valueAfter)
340 : OpNode(Kind::Probe, op, valueBefore, valueAfter), slot(slot) {}
341
342 static bool classof(const LatticeNode *n) { return n->kind == Kind::Probe; }
343};
344
345struct DriveNode : public OpNode {
346 DefSlot slot;
347 Def *def;
348
349 DriveNode(DriveLikeOp op, Value slot, Def *def, LatticeValue *valueBefore,
350 LatticeValue *valueAfter)
351 : OpNode(Kind::Drive, op, valueBefore, valueAfter),
352 slot(isDeltaDrive(op) ? delayedSlot(slot) : blockingSlot(slot)),
353 def(def) {
355 }
356
357 /// Returns true if the op does not drive an entire slot, but only a part of a
358 /// slot through a projection.
359 bool drivesProjection() const { return op->getOperand(0) != getSlot(slot); }
360
361 /// Return the drive op.
362 DriveLikeOp getDriveOp() const { return cast<DriveLikeOp>(op); }
363
364 static bool classof(const LatticeNode *n) { return n->kind == Kind::Drive; }
365};
366
367struct SlotNode : public OpNode {
368 /// The initializer, or a probe inserted after an uninitialized declaration
369 /// if its value is needed before the first unconditional full write.
370 Def *def;
371
372 SlotNode(Operation *op, Def *def, LatticeValue *valueBefore,
373 LatticeValue *valueAfter)
374 : OpNode(Kind::Slot, op, valueBefore, valueAfter), def(def) {}
375
376 bool isSignal() const { return isa<SignalOp>(op); }
377 DefSlot getSlot() const { return blockingSlot(op->getResult(0)); }
378
379 static bool classof(const LatticeNode *n) { return n->kind == Kind::Slot; }
380};
381
382/// A lattice of block entry and exit nodes, nodes for relevant operations such
383/// as probes and drives, and values flowing between the nodes.
384struct Lattice {
385 /// Create a new value on the lattice.
386 LatticeValue *createValue() {
387 auto *value = new (valueAllocator.Allocate()) LatticeValue();
388 values.push_back(value);
389 return value;
390 }
391
392 /// Create a new node on the lattice.
393 template <class T, typename... Args>
394 T *createNode(Args... args) {
395 auto *node =
396 new (getAllocator<T>().Allocate()) T(std::forward<Args>(args)...);
397 nodes.push_back(node);
398 return node;
399 }
400
401 /// Create a new reaching definition.
402 template <typename... Args>
403 Def *createDef(Args... args) {
404 auto *def = new (defAllocator.Allocate()) Def(std::forward<Args>(args)...);
405 defs.push_back(def);
406 return def;
407 }
408
409 /// Create a new reaching definition for an existing value in the IR.
410 Def *createDef(Value value, DriveCondition mode) {
411 auto &slot = defsForValues[{value, mode}];
412 if (!slot) {
413 slot = new (defAllocator.Allocate()) Def(value, mode);
414 defs.push_back(slot);
415 }
416 return slot;
417 }
418
419#ifndef NDEBUG
420 void dump(llvm::raw_ostream &os = llvm::dbgs());
421#endif
422
423 /// All nodes in the lattice.
424 std::vector<LatticeNode *> nodes;
425 /// All values in the lattice.
426 std::vector<LatticeValue *> values;
427 /// All reaching defs in the lattice.
428 std::vector<Def *> defs;
429 /// The reaching defs for concrete values in the IR. This map is used to
430 /// create a single def for the same SSA value to allow for pointer equality
431 /// comparisons.
432 DenseMap<std::pair<Value, DriveCondition>, Def *> defsForValues;
433
434private:
435 SpecificBumpPtrAllocator<LatticeValue> valueAllocator;
436 SpecificBumpPtrAllocator<Def> defAllocator;
437 SpecificBumpPtrAllocator<BlockEntry> blockEntryAllocator;
438 SpecificBumpPtrAllocator<BlockExit> blockExitAllocator;
439 SpecificBumpPtrAllocator<ProbeNode> probeAllocator;
440 SpecificBumpPtrAllocator<DriveNode> driveAllocator;
441 SpecificBumpPtrAllocator<SlotNode> slotAllocator;
442
443 // Helper function to get the correct allocator given a lattice node class.
444 template <class T>
445 SpecificBumpPtrAllocator<T> &getAllocator();
446};
447
448// Specializations for the `getAllocator` template that map node types to the
449// correct allocator.
450template <>
451SpecificBumpPtrAllocator<BlockEntry> &Lattice::getAllocator() {
452 return blockEntryAllocator;
453}
454template <>
455SpecificBumpPtrAllocator<BlockExit> &Lattice::getAllocator() {
456 return blockExitAllocator;
457}
458template <>
459SpecificBumpPtrAllocator<ProbeNode> &Lattice::getAllocator() {
460 return probeAllocator;
461}
462template <>
463SpecificBumpPtrAllocator<DriveNode> &Lattice::getAllocator() {
464 return driveAllocator;
465}
466template <>
467SpecificBumpPtrAllocator<SlotNode> &Lattice::getAllocator() {
468 return slotAllocator;
469}
470
471} // namespace
472
473#ifndef NDEBUG
474/// Print the lattice in human-readable form. Useful for debugging.
475void Lattice::dump(llvm::raw_ostream &os) {
476 // Helper functions to quickly come up with unique names for things.
477 llvm::MapVector<Block *, unsigned> blockNames;
478 llvm::MapVector<Value, unsigned> memNames;
479 llvm::MapVector<Def *, unsigned> defNames;
480
481 auto blockName = [&](Block *block) {
482 unsigned id = blockNames.insert({block, blockNames.size()}).first->second;
483 return std::string("bb") + llvm::utostr(id);
484 };
485
486 auto memName = [&](DefSlot value) {
487 unsigned id =
488 memNames.insert({getSlot(value), memNames.size()}).first->second;
489 return std::string("mem") + llvm::utostr(id) +
490 (isDelayed(value) ? "#" : "");
491 };
492
493 auto defName = [&](Def *def) {
494 unsigned id = defNames.insert({def, defNames.size()}).first->second;
495 return std::string("def") + llvm::utostr(id);
496 };
497
498 // Ensure the blocks are named in the order they were created.
499 for (auto *node : nodes)
500 if (auto *entry = dyn_cast<BlockEntry>(node))
501 blockName(entry->block);
502
503 // Iterate over all block entry nodes.
504 os << "lattice {\n";
505 for (auto *node : nodes) {
506 auto *entry = dyn_cast<BlockEntry>(node);
507 if (!entry)
508 continue;
509
510 // Print the opening braces and predecessors for the block.
511 os << " " << blockName(entry->block) << ":";
512 if (entry->predecessors.empty()) {
513 os << " // no predecessors";
514 } else {
515 os << " // from";
516 for (auto *node : entry->predecessors)
517 os << " " << blockName(node->block);
518 }
519 os << "\n";
520
521 // Print all nodes following the block entry, up until the block exit.
522 auto *value = entry->valueAfter;
523 while (true) {
524 // Print the needed-def flag at this lattice point.
525 if (value->needed)
526 os << " -> need\n";
527 auto printDef = [&](bool delayed, Def *def) {
528 if (!def)
529 return;
530 os << " -> def (" << (delayed ? "delayed" : "blocking")
531 << ")=" << defName(def);
532 if (def->condition.isNever())
533 os << "[N]";
534 else if (def->condition.isAlways())
535 os << "[A]";
536 else
537 os << "[C]";
538 os << "\n";
539 };
540 printDef(false, value->blockingReachingDef);
541 printDef(true, value->delayedReachingDef);
542 if (isa<BlockExit>(value->nodeAfter))
543 break;
544
545 // Print the node.
546 if (auto *node = dyn_cast<ProbeNode>(value->nodeAfter))
547 os << " probe " << memName(blockingSlot(node->slot)) << "\n";
548 else if (auto *node = dyn_cast<DriveNode>(value->nodeAfter))
549 os << " drive " << memName(node->slot) << "\n";
550 else if (auto *node = dyn_cast<SlotNode>(value->nodeAfter))
551 os << " slot " << memName(node->getSlot()) << "\n";
552 else
553 os << " unknown\n";
554
555 // Advance to the next node.
556 value = cast<OpNode>(value->nodeAfter)->valueAfter;
557 }
558
559 // Print the closing braces and successors for the block.
560 auto *exit = cast<BlockExit>(value->nodeAfter);
561 if (isa<WaitOp>(exit->terminator))
562 os << " wait";
563 else if (exit->successors.empty())
564 os << " halt";
565 else
566 os << " goto";
567 for (auto *node : exit->successors)
568 os << " " << blockName(node->block);
569 if (exit->suspends)
570 os << " // suspends";
571 os << "\n";
572 }
573
574 // Dump the memories.
575 for (auto [mem, id] : memNames)
576 os << " mem" << id << ": " << mem << "\n";
577
578 os << "}\n";
579}
580#endif
581
582//===----------------------------------------------------------------------===//
583// Projection Utilities
584//===----------------------------------------------------------------------===//
585
586namespace {
587
588/// A single projection operation, together with the concrete value of the
589/// signal being projected into and the range of the projection. This helper is
590/// useful to unpack a stack of projections to get the targeted value, change
591/// it, and then pack the stack back up into an updated value.
592struct Projection {
593 /// The projection operation.
594 Operation *op;
595 /// The value being projected into. This is not the op's target signal, but
596 /// rather the value of the op's target signal.
597 Value into;
598 /// Range of the signal that is selected by this projection (either a concrete
599 /// range or a dynamic index).
600 ProjectionRange range;
601};
602} // namespace
603
604/// A stack of projection operations.
605using ProjectionStack = SmallVector<Projection>;
606
607/// Collect the `llhd.sig.*` projection ops between `fromSignal` and `toSlot`.
608/// The `fromSignal` value must be derived from `toSlot` through only
609/// `llhd.sig.*` operations. The result is a stack; the op producing
610/// `fromSignal` appears first in the vector, while the final op projecting into
611/// `toSlot` appears last in the vector.
612static ProjectionStack getProjections(Value fromSignal, Value toSlot) {
613 ProjectionStack stack;
614 while (fromSignal != toSlot) {
615 auto *op = cast<OpResult>(fromSignal).getOwner();
616 stack.push_back({op, Value(), {}});
617 fromSignal = op->getOperand(0);
618 }
619 return stack;
620}
621
622/// Resolve a stack of projections by taking a value and descending into its
623/// subelements until the final value targeted by the projection stack remains,
624/// which is then returned. Also updates the `into` fields of the projections in
625/// the stack to represent the concrete value of intermediate projections. This
626/// allows a later `packProjections` to reconstruct the root value with the
627/// field targeted by the projection updated to a different value.
628static Value unpackProjections(OpBuilder &builder, Value value,
629 ProjectionStack &projections) {
630 for (auto &projection : llvm::reverse(projections)) {
631 projection.into = value;
632 value = TypeSwitch<Operation *, Value>(projection.op)
633 .Case<SigArrayGetOp>([&](auto op) {
634 return builder.createOrFold<hw::ArrayGetOp>(
635 op.getLoc(), value, op.getIndex());
636 })
637 .Case<SigStructExtractOp>([&](auto op) {
638 // SigStructExtractOp is used for both struct and union
639 // member access; use the appropriate HW extract op.
640 if (isa<hw::UnionType>(value.getType()))
641 return builder.createOrFold<hw::UnionExtractOp>(
642 op.getLoc(), value, op.getFieldAttr());
643 return builder.createOrFold<hw::StructExtractOp>(
644 op.getLoc(), value, op.getFieldAttr());
645 })
646 .Case<SigExtractOp>([&](auto op) {
647 auto type = cast<RefType>(op.getType()).getNestedType();
648 auto width = type.getIntOrFloatBitWidth();
649 return comb::createDynamicExtract(builder, op.getLoc(), value,
650 op.getLowBit(), width);
651 });
652 }
653 return value;
654}
655
656/// Undo a stack of projections by taking the value of the projected field and
657/// injecting it into the surrounding aggregate value that the projection
658/// targets. This requires the `into` fields to be set to the concrete value of
659/// the intermediate projections.
660///
661/// Example:
662/// ```
663/// auto projections = getProjections(...);
664/// auto fieldValue = unpackProjections(..., aggregateValue, projections);
665/// fieldValue = update(fieldValue);
666/// aggregateValue = packProjections(..., fieldValue, projections);
667/// ```
668static Value packProjections(OpBuilder &builder, Value value,
669 const ProjectionStack &projections) {
670 for (auto projection : projections) {
671 value = TypeSwitch<Operation *, Value>(projection.op)
672 .Case<SigArrayGetOp>([&](auto op) {
673 return builder.createOrFold<hw::ArrayInjectOp>(
674 op.getLoc(), projection.into, op.getIndex(), value);
675 })
676 .Case<SigStructExtractOp>([&](auto op) {
677 // For unions, creating a new value from a single field
678 // replaces the entire union (all fields share storage).
679 if (auto unionTy =
680 dyn_cast<hw::UnionType>(projection.into.getType()))
681 return builder.createOrFold<hw::UnionCreateOp>(
682 op.getLoc(), unionTy, op.getFieldAttr(), value);
683 return builder.createOrFold<hw::StructInjectOp>(
684 op.getLoc(), projection.into, op.getFieldAttr(), value);
685 })
686 .Case<SigExtractOp>([&](auto op) {
687 return comb::createDynamicInject(builder, op.getLoc(),
688 projection.into,
689 op.getLowBit(), value);
690 });
691 }
692 return value;
693}
694
695//===----------------------------------------------------------------------===//
696// Promotion Tree
697//===----------------------------------------------------------------------===//
698
699namespace {
700/// Tree-like structure used to identify the finest-grained promotion slot for
701/// every probe/drive in a region.
702/// Each tree is rooted in an `llhd.sig`. Nodes represent projections from the
703/// root.
704struct PromotionTree {
705 /// An Access represents a probe or drive operation.
706 using Access = Operation *;
707 /// A node in the promotion tree represents a signal (tree root) or a
708 /// projection of it. Some nodes can be promoted to "slots": in this case,
709 /// all reachable projections and accesses are collapsed into the slot node.
710 struct Node {
711 Node(Operation *op) : op(op) {}
712
713 // Helpers to check access types.
714 auto accesses() {
715 return llvm::concat<Access>(directAccesses, foldedAccesses);
716 }
717 bool hasInRegionAccess(const Region &region) {
718 return llvm::any_of(accesses(), [&](Access &access) {
719 return access && access->getParentRegion() == &region;
720 });
721 }
722 bool hasInRegionDeltaDrive(const Region &region) {
723 return llvm::any_of(accesses(), [&](Access &access) {
724 return access->getParentRegion() == &region && isDeltaDrive(access);
725 });
726 }
727 bool hasInRegionBlockingDrive(const Region &region) {
728 return llvm::any_of(accesses(), [&](Access &access) {
729 return access->getParentRegion() == &region && isBlockingDrive(access);
730 });
731 }
732 bool hasInRegionDrive(const Region &region) {
733 return llvm::any_of(accesses(), [&](Access &access) {
734 return access->getParentRegion() == &region && isa<DriveLikeOp>(access);
735 });
736 }
737 bool hasInRegionProjectedDrive(const Region &region) {
738 return llvm::any_of(foldedAccesses, [&](Access &access) {
739 return access->getParentRegion() == &region && isa<DriveLikeOp>(access);
740 });
741 }
742 bool hasProjection() const { return !foldedProjections.empty(); }
743
744 /// Signal or Projection this node corresponds to.
745 Operation *op;
746 /// Direct accesses (probes or drives) of this signal or projection.
747 SmallVector<Access> directAccesses;
748
749 /// Nodes that are promoted to slots become leafs: any reachable op gets
750 /// folded into this node.
751 bool isSlot = false;
752 /// Accesses (probes or drives) reachable from this slot (should be empty if
753 /// isSlot is false).
754 SmallVector<Access> foldedAccesses;
755 /// Projections reachable from this slot (should be empty if isSlot is
756 /// false).
757 SmallVector<Operation *> foldedProjections;
758 };
759
760 /// Build a promotion tree starting from an `llhd.sig` and transitively
761 /// visiting all projections.
762 /// Returns the root node once the whole tree has been computed, or nullptr if
763 /// the tree creation bailed out.
764 /// During this visit, slots are identified using a longest (common) static
765 /// prefix criterion: anytime we find multiple accesses to the same projection
766 /// in this region, or a dynamic projection, the input signal is promoted to a
767 /// slot.
768 /// NOTE: Part of the information held by a PromotionTree could be cached
769 /// globally instead of re-computed separately for each region. Currently the
770 /// blocker is that the folding logic is region-dependent.
771 Node *buildFrom(Operation *signal, Region &region);
772 /// Create a node in this tree.
773 Node *makeNode(Operation *op) {
774 nodes.emplace_back(std::make_unique<Node>(op));
775 return nodes.back().get();
776 }
777
778 /// Nodes owned by this tree.
779 SmallVector<std::unique_ptr<Node>, 8> nodes;
780};
781
782PromotionTree::Node *PromotionTree::buildFrom(Operation *signal,
783 Region &region) {
784 // Create root node.
785 assert(isa<SignalOp>(signal));
786 Node *rootNode = makeNode(signal);
787
788 // Walk projection chain.
789 using WorklistItem = std::tuple<Operation *, Node *, ProjectionStack>;
790 SmallVector<WorklistItem, 4> worklist = {{signal, rootNode, {}}};
791 while (!worklist.empty()) {
792 auto [curOp, curNode, relativePath] = worklist.pop_back_val();
793
794 // Collect all users of the current node and check for promotability.
795 SmallVector<Access, 4> accesses;
796 SmallVector<Projection, 4> projections;
797 for (Operation *user : curOp->getUsers()) {
798 // Bail out if there's any user in a nested region.
799 if (region.isProperAncestor(user->getParentRegion()))
800 return nullptr;
801
802 bool inRegion = user->getParentRegion() == &region;
803
804 if (isa<ProbeOp>(user)) {
805 // Promote to slot if it's directly probed.
806 curNode->isSlot |= inRegion;
807 accesses.push_back(user);
808 } else if (isa<DriveLikeOp>(user)) {
809 // Bail out if we find an unsupported drive type.
810 if (inRegion && !isDeltaDrive(user) && !isBlockingDrive(user))
811 return nullptr;
812 // Promote to slot if it's directly driven.
813 curNode->isSlot |= inRegion;
814 accesses.push_back(user);
815 } else if (isa<SigExtractOp, SigArrayGetOp, SigStructExtractOp>(user)) {
816 auto range = getProjectionRange(user);
817 // We can't reason about this projection: bail out.
818 if (!range)
819 return nullptr;
820 // Promote to slot if it has a dynamic projection.
821 curNode->isSlot |= isDynamic(*range);
822 // Record this projection
823 projections.push_back({user, user->getResult(0), *range});
824 } else {
825 // Unsupported user in this region: bail out.
826 if (inRegion)
827 return nullptr;
828 }
829 }
830
831 // If this node has projections that can overlap there's no finer slot to
832 // find: promote this node to a slot.
833 if (!curNode->isSlot) {
834 auto overlaps = [&](const Projection &p1, const Projection &p2) {
835 return p1.op != p2.op && !isProvablyDisjoint(p1.range, p2.range);
836 };
837 curNode->isSlot |= llvm::any_of(projections, [&](Projection &proj) {
838 return llvm::any_of(projections, [&](Projection &sibling) {
839 return overlaps(proj, sibling);
840 });
841 });
842 }
843
844 // Register accesses.
845 if (relativePath.size() == 0)
846 curNode->directAccesses.append(accesses);
847 else
848 curNode->foldedAccesses.append(accesses);
849
850 // Add projection nodes (or fold if it's a slot) and append to worklist.
851 for (auto &proj : projections) {
852 if (curNode->isSlot) {
853 // For slot nodes, the projection gets folded.
854 curNode->foldedProjections.push_back(proj.op);
855 // Compute the new relative path and append to worklist.
856 auto path = relativePath;
857 path.push_back(proj);
858 worklist.push_back({proj.op, curNode, path});
859 } else {
860 // For non-slot nodes, each outgoing projection gets its own node.
861 auto *projNode = makeNode(proj.op);
862 // Add new node to worklist.
863 // Note: worklist paths are populated only for slots.
864 worklist.push_back({proj.op, projNode, {}});
865 }
866 }
867 }
868
869 return rootNode;
870}
871} // namespace
872
873//===----------------------------------------------------------------------===//
874// Drive/Probe to SSA Value Promotion
875//===----------------------------------------------------------------------===//
876
877namespace {
878/// The main promoter forwarding drives to probes within a region.
879struct Promoter {
880 Promoter(Region &region) : region(region) {}
881 LogicalResult promote();
882
883 void findPromotableSlots();
884 Value resolveSlot(Value projectionOrSlot);
885 void populateSlotOps();
886
887 void computeLiveOutWait();
888 void captureAcrossWait();
889
890 void constructLattice();
891 void propagateBackward();
892 void propagateBackward(LatticeNode *node);
893 void propagateForward();
894 void propagateForward(bool optimisticMerges, DominanceInfo &dominance);
895 void propagateForward(LatticeNode *node, bool optimisticMerges,
896 DominanceInfo &dominance);
897 void markDirty(LatticeNode *node);
898
899 void insertProbeBlocks();
900 void insertProbes();
901 void insertProbes(BlockEntry *node);
902 void insertProbes(SlotNode *node);
903 void hoistSlot(Operation *slotOp);
904
905 void insertDriveBlocks();
906 void insertDrives();
907 void insertDrives(BlockExit *node);
908 void insertDrives(DriveNode *node);
909
910 void resolveDefinitions();
911 void resolveDefinitions(ProbeNode *node);
912 void resolveDefinitions(DriveNode *node);
913 void resolveDefinitionValue(DriveNode *node);
914 void resolveDefinitionCondition(DriveNode *node);
915
916 void insertBlockArgs();
917 bool insertBlockArgs(BlockEntry *node);
918 void replaceValueWith(Value oldValue, Value newValue);
919
920 /// Remove a local `llhd.sig` op if all of its remaining users are drives or
921 /// projections.
922 void removeUnusedLocalSignal(SignalOp signalOp);
923
924 /// Run the lattice analysis and transformation pipeline for `currentSlot`.
925 void promoteSlot();
926
927 /// The region we are promoting in.
928 Region &region;
929
930 /// All wait operations in the region.
931 SmallVector<WaitOp> waitOps;
932 /// Values to capture across waits.
933 llvm::SetVector<Value> liveOutWait;
934 /// Region analyses shared by different stages of the pass.
935 std::unique_ptr<DominanceInfo> dominance;
936 std::unique_ptr<Liveness> liveness;
937
938 /// The slots we are promoting. Mostly `llhd.sig` ops in practice. This
939 /// establishes a deterministic order for slot allocations, such that
940 /// everything else in the pass can operate using unordered maps and sets.
941 SmallVector<Value> slots;
942 /// A mapping from projections to the root slot they are projecting into.
943 SmallDenseMap<Value, Value> projections;
944 /// A set of all promotable signal SSA values. This is the union of `slots`
945 /// and `projections` of those slots.
946 SmallDenseSet<Value> promotable;
947
948 /// The slot currently being analyzed and rewritten. The lattice and all
949 /// per-slot methods operate relative to this value.
950 Value currentSlot;
951
952 /// One `llhd.constant_time` op per block, shared by every drive the pass
953 /// inserts at that block's terminator regardless of which slot triggered the
954 /// insertion.
955 DenseMap<Block *, ConstantTimeOp> delayedTimeCache;
956
957 /// Lattice for the slot currently being promoted. Holds the needed-def
958 /// flag and the pair of reaching-def pointers at every program point, plus
959 /// the bump allocators that own the nodes/values/defs.
960 std::optional<Lattice> lattice;
961 /// A worklist of lattice nodes used within calls to `propagate*`.
962 SmallVector<LatticeNode *> dirtyNodes;
963
964 /// Helper to clean up unused ops.
965 UnusedOpPruner pruner;
966
967 /// Maps slot values to all ops that refer to them. The operation list is
968 /// laid out in the same order as a loop over blocks in the region.
969 DenseMap<Value, SmallVector<Operation *>> slotOps;
970 /// Signals local to the current region.
971 SmallSetVector<Operation *, 4> localSignals;
972};
973} // namespace
974
975LogicalResult Promoter::promote() {
976 if (region.empty())
977 return success();
978
979 computeLiveOutWait();
980 findPromotableSlots();
982
983 // If there are no promotable slots we can still return after ensuring any
984 // values live across waits were captured as block arguments above. This
985 // keeps the pass semantics while allowing wait capturing to run
986 // independently of slot promotion.
987 if (slots.empty())
988 return success();
989
990 // Run the lattice analysis and rewrite once per slot. Each iteration gets
991 // its own fresh lattice with O(1)-sized state per program point, so the
992 // total cost is linear in the number of slots times the number of ops that
993 // contribute to that slot.
994 populateSlotOps();
995 for (auto slot : slots) {
996 currentSlot = slot;
997 promoteSlot();
998 }
999 currentSlot = {};
1000
1001 // Drop region-local signal declarations that are no longer probed.
1002 for (auto *signalOp : localSignals)
1003 removeUnusedLocalSignal(cast<SignalOp>(signalOp));
1004
1005 // Erase operations that have become unused.
1006 pruner.eraseNow();
1007
1008 return success();
1009}
1010
1011/// Run the lattice analysis and transformation pipeline for `currentSlot`.
1012void Promoter::promoteSlot() {
1013 assert(currentSlot && "currentSlot must be set before promoteSlot()");
1014 lattice.emplace();
1015 dirtyNodes.clear();
1016
1017 LLVM_DEBUG(llvm::dbgs() << "Promoting slot " << currentSlot << "\n");
1018
1019 constructLattice();
1020 LLVM_DEBUG({
1021 llvm::dbgs() << "Initial lattice:\n";
1022 lattice->dump();
1023 });
1024
1025 // Propagate the needed-def flag backward across the lattice.
1026 propagateBackward();
1027 LLVM_DEBUG({
1028 llvm::dbgs() << "After backward propagation:\n";
1029 lattice->dump();
1030 });
1031
1032 // Insert probes wherever a def is needed for the first time.
1033 insertProbeBlocks();
1034 insertProbes();
1035 LLVM_DEBUG({
1036 llvm::dbgs() << "After probe insertion:\n";
1037 lattice->dump();
1038 });
1039
1040 // Propagate the reaching-def pointers forward across the lattice.
1041 propagateForward();
1042 LLVM_DEBUG({
1043 llvm::dbgs() << "After forward propagation:\n";
1044 lattice->dump();
1045 });
1046
1047 // Resolve definitions.
1048 resolveDefinitions();
1049
1050 // Insert drives wherever a reaching def can no longer propagate.
1051 insertDriveBlocks();
1052 insertDrives();
1053 LLVM_DEBUG({
1054 llvm::dbgs() << "After def resolution and drive insertion:\n";
1055 lattice->dump();
1056 });
1057
1058 // Insert the necessary block arguments.
1059 insertBlockArgs();
1060
1061 // If this slot come from a region-local signal, mark it as a candidate for
1062 // later -- will be dropped if not needed.
1063 if (auto *signalOp = getRootSignal(currentSlot))
1064 if (signalOp->getParentRegion() == &region)
1065 localSignals.insert(signalOp);
1066
1067 // Release the lattice so the bump allocators free their slabs before the
1068 // next slot runs.
1069 lattice.reset();
1070}
1071
1072/// Identify any promotable slots probed or driven under the current region.
1073void Promoter::findPromotableSlots() {
1074 SmallPtrSet<Value, 8> seenSlots;
1075 SmallPtrSet<Operation *, 8> seenSignals;
1076
1077 // Create a promotion tree for every signal driven in this region.
1078 PromotionTree ptree;
1079 region.walk([&](Operation *op) {
1080 for (auto operand : op->getOperands()) {
1081 if (!seenSlots.insert(operand).second)
1082 continue;
1083 // Go back in the projection chain until you find a SignalOp.
1084 // Other signals, such as the ones brought into a module through a port,
1085 // have an unknown aliasing relationship with the other ports.
1086 auto *root = getRootSignal(operand);
1087 if (!root)
1088 continue;
1089 if (!seenSignals.insert(root).second)
1090 continue;
1091
1092 unsigned prevSize = ptree.nodes.size();
1093 auto *rootNode = ptree.buildFrom(root, region);
1094 // Bail out if the root signal has uses we cannot reason about.
1095 if (!rootNode) {
1096 ptree.nodes.pop_back_n(ptree.nodes.size() - prevSize);
1097 continue;
1098 }
1099 }
1100 });
1101 // Select only the promotable slots.
1102 for (auto &node : ptree.nodes) {
1103 // Select only slots that are accessed in this region.
1104 if (!node->isSlot || !node->hasInRegionAccess(region))
1105 continue;
1106
1107 // Don't promote slots that have projections and a mix of blocking and
1108 // delta drives. A blocking drive erases the delayed reaching definition,
1109 // which leaves delta projection drives without a reaching definition.
1110 if (node->hasProjection() && node->hasInRegionBlockingDrive(region) &&
1111 node->hasInRegionDeltaDrive(region))
1112 continue;
1113
1114 // Mem2Reg may have to materialize a zero value for promoted slots. Skip
1115 // signal types for which we cannot create a suitable default.
1116 Value slotVal = node->op->getResult(0);
1117 if (!isPromotableSlotType(getStoredType(slotVal)))
1118 continue;
1119
1120 // Check if promoting this slot would fold in a projection whose parent
1121 // value is captured across a wait boundary. Capturing rewrites uses of
1122 // the parent value beyond the wait to a new block argument, which would
1123 // sever the operand(0) chain the projection stacks are built from.
1124 if (llvm::any_of(node->foldedProjections, [&](Operation *proj) {
1125 return liveOutWait.contains(proj->getOperand(0));
1126 }))
1127 continue;
1128
1129 // Valid slot reached.
1130 slots.push_back(slotVal);
1131 for (auto *proj : node->foldedProjections)
1132 projections[proj->getResult(0)] = slotVal;
1133 }
1134 // Populate `promotable` with the slots and projections we are promoting.
1135 promotable.insert(slots.begin(), slots.end());
1136 projections.remove_if([&](auto elem) {
1137 auto [projection, slot] = elem;
1138 return !promotable.contains(slot);
1139 });
1140 for (auto [projection, slot] : projections)
1141 promotable.insert(projection);
1142
1143 LLVM_DEBUG(llvm::dbgs() << "Found " << slots.size() << " promotable slots, "
1144 << promotable.size() << " promotable values\n");
1145}
1146
1147/// Resolve SSA values in `projection` to the `slot` they are projecting into.
1148/// Simply returns the given value if it is not in `projections`.
1149Value Promoter::resolveSlot(Value projectionOrSlot) {
1150 if (auto slot = projections.lookup(projectionOrSlot))
1151 return slot;
1152 return projectionOrSlot;
1153}
1154
1155/// Collect any probes that are live across an `llhd.wait`.
1156/// These will be later explicitly captured as block arguments by
1157/// captureAcrossWait().
1158void Promoter::computeLiveOutWait() {
1159 if (region.hasOneBlock())
1160 return;
1161
1162 for (auto &block : region)
1163 if (auto waitOp = dyn_cast<WaitOp>(block.getTerminator()))
1164 waitOps.push_back(waitOp);
1165
1166 if (waitOps.empty())
1167 return;
1168
1169 dominance = std::make_unique<DominanceInfo>(region.getParentOp());
1170 liveness = std::make_unique<Liveness>(region.getParentOp());
1171
1172 auto isDefinedInRegion = [&](Value v) {
1173 return v.getParentRegion() == &region;
1174 };
1175
1176 for (auto waitOp : waitOps) {
1177 Block *waitBlock = waitOp->getBlock();
1178 const auto &liveOutValues = liveness->getLiveOut(waitBlock);
1179
1180 for (Value v : liveOutValues) {
1181 if (!isDefinedInRegion(v))
1182 continue;
1183 liveOutWait.insert(v);
1184 }
1185 }
1186}
1187
1188/// Explicitly capture any probes that are live across an `llhd.wait` as block
1189/// arguments and destination operand of that wait. This ensures that replacing
1190/// the probe with a reaching definition later on will capture the value of the
1191/// reaching definition before the wait.
1192void Promoter::captureAcrossWait() {
1193 if (!dominance || !liveness)
1194 return;
1195 for (Value v : liveOutWait)
1196 llhd::captureAcrossWait(v, waitOps, *liveness, *dominance);
1197}
1198
1199//===----------------------------------------------------------------------===//
1200// Lattice Construction and Propagation
1201//===----------------------------------------------------------------------===//
1202
1203/// Preprocess all ops in the current region to populate `slotOps`.
1204///
1205/// This avoids a repeated linear walk of the region in every call to
1206/// `constructLattice`.
1207void Promoter::populateSlotOps() {
1208 for (auto &block : region) {
1209 for (auto &op : block.without_terminator()) {
1210 Value slot = TypeSwitch<Operation *, Value>(&op)
1211 .Case([&](ProbeOp op) {
1212 if (promotable.contains(op.getSignal()))
1213 return resolveSlot(op.getSignal());
1214 return Value();
1215 })
1216 .Case([&](DriveLikeOp op) {
1217 if (promotable.contains(op.getDriven()))
1218 return resolveSlot(op.getDriven());
1219 return Value();
1220 })
1221 .Case<SigExtractOp, SigArrayGetOp, SigStructExtractOp>(
1222 [&](Operation *op) -> Value {
1223 if (llvm::is_contained(slots, op->getResult(0)))
1224 return op->getResult(0);
1225 return Value();
1226 })
1227 .Case([&](SignalOp op) { return op.getResult(); })
1228 .Default([&](Operation *) { return Value(); });
1229 if (slot)
1230 slotOps[slot].push_back(&op);
1231 }
1232 }
1233}
1234
1235/// Populate the lattice with nodes and values corresponding to the blocks and
1236/// to the operations in the region that touch `currentSlot`. Ops that touch
1237/// other slots are skipped entirely — they're transparent to this slot's
1238/// analysis.
1239void Promoter::constructLattice() {
1240 assert(currentSlot && "constructLattice requires currentSlot");
1241
1242 // Get all operations that correspond to the current slot in the region. These
1243 // are arranged in the same order as a region walk.
1244 ArrayRef<Operation *> currentSlotOps = slotOps[currentSlot];
1245
1246 // Create entry nodes for each block.
1247 SmallDenseMap<Block *, BlockEntry *, 8> blockEntries;
1248 for (auto &block : region) {
1249 auto *entry =
1250 lattice->createNode<BlockEntry>(&block, lattice->createValue());
1251 blockEntries.insert({&block, entry});
1252 }
1253
1254 // Create nodes for each operation that touches `currentSlot`.
1255 for (auto &block : region) {
1256 auto *valueBefore = blockEntries.lookup(&block)->valueAfter;
1257
1258 // Handle operations. All operations within this block will exist in the
1259 // prefix of currentSlotOps.
1260 ArrayRef<Operation *> blockOps = currentSlotOps.take_while(
1261 [&](Operation *op) { return op->getBlock() == &block; });
1262 currentSlotOps = currentSlotOps.drop_front(blockOps.size());
1263
1264 for (Operation *op : blockOps) {
1265 // Handle probes.
1266 if (auto probeOp = dyn_cast<ProbeOp>(op)) {
1267 if (!promotable.contains(probeOp.getSignal()))
1268 continue;
1269 if (resolveSlot(probeOp.getSignal()) != currentSlot)
1270 continue;
1271 auto *node = lattice->createNode<ProbeNode>(
1272 probeOp, currentSlot, valueBefore, lattice->createValue());
1273 valueBefore = node->valueAfter;
1274 continue;
1275 }
1276
1277 // Handle drives.
1278 if (auto driveOp = dyn_cast<DriveLikeOp>(op)) {
1279 if (!isBlockingDrive(driveOp) && !isDeltaDrive(driveOp))
1280 continue;
1281 auto signal = driveOp.getDriven();
1282 if (!promotable.contains(signal))
1283 continue;
1284 if (resolveSlot(signal) != currentSlot)
1285 continue;
1286 auto condition = DriveCondition::always();
1287 if (auto enable = driveOp.getEnable())
1288 condition = DriveCondition::conditional(enable);
1289 // Drives that target a slot directly provide the driven value as a
1290 // definition for the slot. Drives to projections have their value
1291 // calculated later on.
1292 auto *def =
1293 signal == currentSlot
1294 ? lattice->createDef(driveOp.getValue(), condition)
1295 : lattice->createDef(driveOp->getBlock(),
1296 getStoredType(currentSlot), condition);
1297 auto *node = lattice->createNode<DriveNode>(
1298 driveOp, currentSlot, def, valueBefore, lattice->createValue());
1299 valueBefore = node->valueAfter;
1300 continue;
1301 }
1302
1303 // Handle local slots.
1304 if (isa<SignalOp, SigExtractOp, SigArrayGetOp, SigStructExtractOp>(op)) {
1305 if (op->getResult(0) != currentSlot)
1306 continue;
1307 Def *def = nullptr;
1308 // Only signals have an initial value.
1309 if (auto signalOp = dyn_cast<SignalOp>(op))
1310 if (auto init = signalOp.getInit())
1311 def = lattice->createDef(init, DriveCondition::never());
1312 auto *node = lattice->createNode<SlotNode>(op, def, valueBefore,
1313 lattice->createValue());
1314 valueBefore = node->valueAfter;
1315 continue;
1316 }
1317 }
1318
1319 // Create the exit node for the block.
1320 auto *exit = lattice->createNode<BlockExit>(&block, valueBefore);
1321 for (auto *otherBlock : exit->terminator->getSuccessors()) {
1322 auto *otherEntry = blockEntries.lookup(otherBlock);
1323 exit->successors.push_back(otherEntry);
1324 otherEntry->predecessors.push_back(exit);
1325 }
1326 }
1327}
1328
1329/// Propagate the lattice values backwards against control flow until a fixed
1330/// point is reached.
1331void Promoter::propagateBackward() {
1332 for (auto *node : lattice->nodes)
1333 propagateBackward(node);
1334 SmallVector<LatticeNode *> nodes;
1335 while (!dirtyNodes.empty()) {
1336 std::swap(dirtyNodes, nodes);
1337 for (auto *node : nodes) {
1338 node->dirty = false;
1339 propagateBackward(node);
1340 }
1341 nodes.clear();
1342 }
1343}
1344
1345/// Propagate the lattice value after a node backward to the value before a
1346/// node, updating the `needed` flag at the incoming value.
1347void Promoter::propagateBackward(LatticeNode *node) {
1348 auto update = [&](LatticeValue *value, bool needed) {
1349 if (value->needed != needed) {
1350 value->needed = needed;
1351 markDirty(value->nodeBefore);
1352 }
1353 };
1354
1355 // Probes need a definition for the probed slot to be available.
1356 if (auto *probe = dyn_cast<ProbeNode>(node)) {
1357 update(probe->valueBefore, true);
1358 return;
1359 }
1360
1361 // Blocking unconditional drives to an entire slot kill the need for a
1362 // definition to be available, since they provide a definition themselves.
1363 // Conditional drives propagate the need for a definition, since they have to
1364 // forward an incoming reaching def in case they are disabled. Drives to
1365 // projections need a definition to be available such that they can partially
1366 // update it.
1367 if (auto *drive = dyn_cast<DriveNode>(node)) {
1368 bool needed = drive->valueAfter->needed;
1369 if (drive->drivesProjection())
1370 needed = true;
1371 else if (!isDelayed(drive->slot) && !drive->getDriveOp().getEnable())
1372 needed = false;
1373 update(drive->valueBefore, needed);
1374 return;
1375 }
1376
1377 // A slot's storage becomes available at its defining op: signal declarations
1378 // allocate it, projections name it for the first time. Forward propagation
1379 // overwrites the slot's value there in either case, so nothing from above
1380 // ever flows through and no definition is ever needed above the op. This also
1381 // keeps the need, and therefore any probe inserted to satisfy it, inside the
1382 // part of the region that the slot dominates.
1383 if (auto *slot = dyn_cast<SlotNode>(node)) {
1384 update(slot->valueBefore, false);
1385 return;
1386 }
1387
1388 // Block entries simply trigger updates to all their predecessors.
1389 if (auto *entry = dyn_cast<BlockEntry>(node)) {
1390 for (auto *predecessor : entry->predecessors)
1391 markDirty(predecessor);
1392 return;
1393 }
1394
1395 // Block exits merge any needed definitions from their successors.
1396 if (auto *exit = dyn_cast<BlockExit>(node)) {
1397 if (exit->suspends)
1398 return;
1399 bool needed = false;
1400 for (auto *successor : exit->successors)
1401 needed |= successor->valueAfter->needed;
1402 update(exit->valueBefore, needed);
1403 return;
1404 }
1405
1406 assert(false && "unhandled node in backward propagation");
1407}
1408
1409void Promoter::propagateForward() {
1410 DominanceInfo dominance(region.getParentOp());
1411 propagateForward(true, dominance);
1412 propagateForward(false, dominance);
1413}
1414
1415/// Propagate the lattice values forwards along with control flow until a fixed
1416/// point is reached. If `optimisticMerges` is true, block entry points
1417/// propagate definitions from their predecessors into the block without
1418/// creating a merge definition even if the definition is not available in all
1419/// predecessors. This is overly optimistic, but initially helps definitions
1420/// propagate through loop structures. If `optimisticMerges` is false, block
1421/// entry points create merge definitions for definitions that are not available
1422/// in all predecessors.
1423void Promoter::propagateForward(bool optimisticMerges,
1424 DominanceInfo &dominance) {
1425 for (auto *node : lattice->nodes)
1426 propagateForward(node, optimisticMerges, dominance);
1427 SmallVector<LatticeNode *> nodes;
1428 while (!dirtyNodes.empty()) {
1429 std::swap(dirtyNodes, nodes);
1430 for (auto *node : nodes) {
1431 node->dirty = false;
1432 propagateForward(node, optimisticMerges, dominance);
1433 }
1434 nodes.clear();
1435 }
1436}
1437
1438/// Propagate the lattice value before a node forward to the value after a
1439/// node, updating the blocking and delayed reaching-def pointers at the
1440/// outgoing value.
1441void Promoter::propagateForward(LatticeNode *node, bool optimisticMerges,
1442 DominanceInfo &dominance) {
1443 auto update = [&](LatticeValue *value, Def *blocking, Def *delayed) {
1444 if (value->blockingReachingDef != blocking ||
1445 value->delayedReachingDef != delayed) {
1446 value->blockingReachingDef = blocking;
1447 value->delayedReachingDef = delayed;
1448 markDirty(value->nodeAfter);
1449 }
1450 };
1451
1452 // Probes simply propagate any reaching defs.
1453 if (auto *probe = dyn_cast<ProbeNode>(node)) {
1454 update(probe->valueAfter, probe->valueBefore->blockingReachingDef,
1455 probe->valueBefore->delayedReachingDef);
1456 return;
1457 }
1458
1459 // Drives propagate the driven value as a reaching def. Blocking drives kill
1460 // earlier non-blocking drives. This reflects Verilog and VHDL behaviour,
1461 // where a drive sequence like
1462 //
1463 // a <= #10ns 42; // A
1464 // a <= 43; // B
1465 // a = 44; // C
1466 //
1467 // would see (B) override (A), because it happens earlier, and (C) override
1468 // (B), because it in turn happens earlier.
1469 if (auto *drive = dyn_cast<DriveNode>(node)) {
1470 Def *blocking = drive->valueBefore->blockingReachingDef;
1471 Def *delayed = drive->valueBefore->delayedReachingDef;
1472 bool driveDelayed = isDelayed(drive->slot);
1473
1474 // If the drive is conditional or driving a projection of a slot, merge any
1475 // incoming reaching def into the reaching def created by the drive. This is
1476 // necessary since a conditional drive following an unconditional drive may
1477 // have to insert a multiplexer to forward to subsequent probes.
1478 if (drive->drivesProjection() || drive->getDriveOp().getEnable()) {
1479 Def *inDef = driveDelayed ? delayed : blocking;
1480 if (inDef) {
1481 if (drive->def->value != inDef->value)
1482 drive->def->value = {};
1483 if (inDef->condition.isAlways() || drive->def->condition.isAlways())
1484 drive->def->condition = DriveCondition::always();
1485 else if (drive->def->condition != inDef->condition)
1486 drive->def->condition = DriveCondition::conditional();
1487 }
1488 }
1489
1490 if (driveDelayed) {
1491 delayed = drive->def;
1492 } else {
1493 blocking = drive->def;
1494 // A blocking drive kills any pending delta drive at the same slot.
1495 delayed = nullptr;
1496 }
1497 update(drive->valueAfter, blocking, delayed);
1498 return;
1499 }
1500
1501 // Signals provide their initializer or inserted probe as the starting value
1502 // for both blocking and delayed drives. Its "never" condition also clears
1503 // any pending drives from an earlier execution of the declaration.
1504 if (auto *slot = dyn_cast<SlotNode>(node)) {
1505 update(slot->valueAfter, slot->def, slot->isSignal() ? slot->def : nullptr);
1506 return;
1507 }
1508
1509 // Block entry points merge reaching defs from their predecessors, creating
1510 // new merge defs where predecessors disagree.
1511 if (auto *entry = dyn_cast<BlockEntry>(node)) {
1512 // Inserted probes supersede anything coming from predecessors, for both
1513 // the blocking and delayed flavors.
1514 if (entry->insertedProbe) {
1515 update(entry->valueAfter, entry->insertedProbe, entry->insertedProbe);
1516 return;
1517 }
1518
1519 // Do not propagate reaching defs past a block whose defining op does not
1520 // dominate this entry, or whose predecessor set contains any suspending
1521 // block.
1522 Block *slotBlock = currentSlot.getDefiningOp()->getBlock();
1523 bool slotDominates = dominance.dominates(slotBlock, entry->block);
1524 bool anyPredSuspends =
1525 llvm::any_of(entry->predecessors, [](auto *p) { return p->suspends; });
1526
1527 auto mergeFlavor = [&](bool delayed) -> Def * {
1528 if (!slotDominates || anyPredSuspends)
1529 return nullptr;
1530
1531 // Bail early if no predecessor provides a def for this flavor.
1532 if (llvm::all_of(entry->predecessors, [&](auto *p) {
1533 return !p->valueBefore->getReachingDef(delayed);
1534 }))
1535 return nullptr;
1536
1537 // Walk predecessors to determine whether all agree on the same def and
1538 // the same drive condition.
1539 Def *common = nullptr;
1540 DriveCondition cond = DriveCondition::never();
1541 bool first = true;
1542 for (auto *pred : entry->predecessors) {
1543 Def *predDef = pred->valueBefore->getReachingDef(delayed);
1544 if (!predDef && optimisticMerges)
1545 continue;
1546 DriveCondition predCond =
1547 predDef ? predDef->condition : DriveCondition::never();
1548 if (first) {
1549 common = predDef;
1550 cond = predCond;
1551 first = false;
1552 continue;
1553 }
1554 if (common != predDef)
1555 common = nullptr;
1556 if (cond != predCond)
1557 cond = DriveCondition::conditional();
1558 }
1559
1560 if (first)
1561 return nullptr;
1562
1563 // Once a merge def exists at this entry, keep returning it. The value
1564 // here can otherwise flip between the cached `merged` (when
1565 // predecessors disagree) and `common` (when they happen to coincide on
1566 // a non-null def via back-edge propagation), preventing the fixpoint
1567 // loop from converging on cyclic CFGs.
1568 Def *&merged = delayed ? entry->delayedMerged : entry->blockingMerged;
1569 if (merged) {
1570 merged->condition = cond;
1571 return merged;
1572 }
1573
1574 // If all predecessors agree on the same concrete def, use it as-is.
1575 if (common)
1576 return common;
1577
1578 // Otherwise create a merge def for this disagreement.
1579 auto slot =
1580 delayed ? delayedSlot(currentSlot) : blockingSlot(currentSlot);
1581 merged = lattice->createDef(entry->block, getStoredType(slot), cond);
1582 return merged;
1583 };
1584
1585 Def *newBlocking = mergeFlavor(/*delayed=*/false);
1586 Def *newDelayed = mergeFlavor(/*delayed=*/true);
1587 update(entry->valueAfter, newBlocking, newDelayed);
1588 return;
1589 }
1590
1591 // Block exits simply trigger updates to all their successors.
1592 if (auto *exit = dyn_cast<BlockExit>(node)) {
1593 for (auto *successor : exit->successors)
1594 markDirty(successor);
1595 return;
1596 }
1597
1598 assert(false && "unhandled node in forward propagation");
1599}
1600
1601/// Mark a lattice node to be updated during propagation.
1602void Promoter::markDirty(LatticeNode *node) {
1603 assert(node);
1604 if (node->dirty)
1605 return;
1606 node->dirty = true;
1607 dirtyNodes.push_back(node);
1608}
1609
1610//===----------------------------------------------------------------------===//
1611// Drive/Probe Insertion
1612//===----------------------------------------------------------------------===//
1613
1614/// Insert additional probe blocks where needed. This can happen if a definition
1615/// is needed in a block which has a suspending and non-suspending predecessor.
1616/// In that case we would like to insert probes in the predecessor blocks, but
1617/// cannot do so because of the suspending predecessor.
1618void Promoter::insertProbeBlocks() {
1619 // Find predecessor/successor edges where the current slot is needed at the
1620 // successor but not carried past one of the successor's predecessors. An
1621 // extra probe block is inserted on such edges.
1622 SmallDenseSet<std::pair<BlockExit *, BlockEntry *>, 1> worklist;
1623 for (auto *node : lattice->nodes) {
1624 auto *entry = dyn_cast<BlockEntry>(node);
1625 if (!entry || !entry->valueAfter->needed)
1626 continue;
1627 unsigned numIncoming = 0;
1628 for (auto *predecessor : entry->predecessors)
1629 if (predecessor->valueBefore->needed)
1630 ++numIncoming;
1631 if (numIncoming == 0 || numIncoming == entry->predecessors.size())
1632 continue;
1633 for (auto *predecessor : entry->predecessors)
1634 if (!predecessor->valueBefore->needed)
1635 worklist.insert({predecessor, entry});
1636 }
1637
1638 // Insert probe blocks after all blocks we have identified.
1639 for (auto [predecessor, successor] : worklist) {
1640 LLVM_DEBUG(llvm::dbgs() << "- Inserting probe block towards " << successor
1641 << " after " << *predecessor->terminator << "\n");
1642 OpBuilder builder(predecessor->terminator);
1643 auto *newBlock = builder.createBlock(successor->block);
1644 for (auto oldArg : successor->block->getArguments())
1645 newBlock->addArgument(oldArg.getType(), oldArg.getLoc());
1646 cf::BranchOp::create(builder, predecessor->terminator->getLoc(),
1647 successor->block, newBlock->getArguments());
1648 for (auto &blockOp : predecessor->terminator->getBlockOperands())
1649 if (blockOp.get() == successor->block)
1650 blockOp.set(newBlock);
1651
1652 // Create new nodes in the lattice for the added block.
1653 auto *value = lattice->createValue();
1654 value->needed = successor->valueAfter->needed;
1655 auto *newEntry = lattice->createNode<BlockEntry>(newBlock, value);
1656 auto *newExit = lattice->createNode<BlockExit>(newBlock, value);
1657 newEntry->predecessors.push_back(predecessor);
1658 newExit->successors.push_back(successor);
1659 llvm::replace(successor->predecessors, predecessor, newExit);
1660 llvm::replace(predecessor->successors, successor, newEntry);
1661 }
1662}
1663
1664/// Insert probes wherever a definition is needed for the first time. This is
1665/// the case in the entry block, after any suspensions, and after uninitialized
1666/// signal declarations.
1667void Promoter::insertProbes() {
1668 for (auto *node : lattice->nodes) {
1669 if (auto *entry = dyn_cast<BlockEntry>(node))
1670 insertProbes(entry);
1671 else if (auto *slot = dyn_cast<SlotNode>(node))
1672 insertProbes(slot);
1673 }
1674}
1675
1676/// Insert a probe directly after a SlotNode that is not a SignalOp. Also move
1677/// the slot's projection chain in front of the region's parent op, such that
1678/// the slot is defined outside the region like a regular signal.
1679void Promoter::insertProbes(SlotNode *node) {
1680 auto *op = node->op;
1681
1682 if (!node->def && node->valueAfter->needed) {
1683 OpBuilder builder(op);
1684 builder.setInsertionPointAfter(op);
1685 auto value = ProbeOp::create(builder, currentSlot.getLoc(), currentSlot);
1686 node->def = lattice->createDef(value, DriveCondition::never());
1687
1688 LLVM_DEBUG(llvm::dbgs() << "- Inserting probe for " << currentSlot
1689 << " after " << *op << "\n");
1690 }
1691
1692 // The probe stays where the projection was, so moving the projection out
1693 // does not change when the slot is read.
1694 hoistSlot(op);
1695}
1696
1697/// Move the in-region part of a slot's projection chain in front of the
1698/// region's parent op. Slots are reached from their root signal through
1699/// projections with constant indices only, so the only other ops that may have
1700/// to move along are the constants. Does nothing if the chain bottoms out in a
1701/// signal declared inside the region.
1702void Promoter::hoistSlot(Operation *slotOp) {
1703 auto isInRegion = [&](Value value) {
1704 return region.isAncestor(value.getParentRegion());
1705 };
1706
1707 // Collect the projections inside the region, from the slot up to the first
1708 // projection whose input is defined outside the region. Each projection is
1709 // followed by the constants it uses.
1710 SmallVector<Operation *> toMove;
1711 auto *curOp = slotOp;
1712 while (true) {
1713 if (!isProjection(curOp))
1714 return;
1715 toMove.push_back(curOp);
1716 for (auto index : curOp->getOperands().drop_front()) {
1717 if (!isInRegion(index))
1718 continue;
1719 auto *indexOp = index.getDefiningOp();
1720 if (!indexOp || !indexOp->hasTrait<OpTrait::ConstantLike>())
1721 return;
1722 toMove.push_back(indexOp);
1723 }
1724 auto input = curOp->getOperand(0);
1725 if (!isInRegion(input))
1726 break;
1727 curOp = input.getDefiningOp();
1728 if (!curOp)
1729 return;
1730 }
1731
1732 // Move the ops out top-down, such that every op ends up after its operands.
1733 // Constants shared by multiple projections only move once.
1734 for (auto *op : llvm::reverse(toMove)) {
1735 if (!region.isAncestor(op->getParentRegion()))
1736 continue;
1737 LLVM_DEBUG(llvm::dbgs() << "- Hoisting " << *op << "\n");
1738 op->moveBefore(region.getParentOp());
1739 }
1740}
1741
1742/// Insert a probe at the beginning of the block for the current slot, if it
1743/// is needed here but not already provided by all predecessors.
1744void Promoter::insertProbes(BlockEntry *node) {
1745 if (!node->valueAfter->needed)
1746 return;
1747 if (!node->predecessors.empty() &&
1748 llvm::all_of(node->predecessors, [](auto *predecessor) {
1749 return predecessor->valueBefore->needed;
1750 }))
1751 return;
1752 LLVM_DEBUG(llvm::dbgs() << "- Inserting probe for " << currentSlot
1753 << " in block " << node->block << "\n");
1754 auto builder = OpBuilder::atBlockBegin(node->block);
1755 // If the slot is defined in this same block, insert after its defining op.
1756 if (Operation *op = currentSlot.getDefiningOp())
1757 if (op->getBlock() == node->block)
1758 builder.setInsertionPointAfterValue(currentSlot);
1759 auto value = ProbeOp::create(builder, currentSlot.getLoc(), currentSlot);
1760 auto *def = lattice->createDef(value, DriveCondition::never());
1761 node->insertedProbe = def;
1762}
1763
1764/// Insert additional drive blocks where needed. This can happen if a definition
1765/// continues into some of a block's successors, but not all of them.
1766void Promoter::insertDriveBlocks() {
1767 // Find exit/successor edges where the current slot reaches the exit with a
1768 // non-never drive condition but isn't propagated through all successors.
1769 // Test the blocking and delayed flavors independently.
1770 auto partialAt = [](LatticeValue *before, LatticeValue *after, bool delayed,
1771 unsigned totalSuccessors) {
1772 Def *def = before->getReachingDef(delayed);
1773 if (!def || def->condition.isNever())
1774 return false;
1775 (void)totalSuccessors;
1776 return !after->getReachingDef(delayed);
1777 };
1778
1779 SmallDenseSet<std::pair<BlockExit *, BlockEntry *>, 1> worklist;
1780 for (auto *node : lattice->nodes) {
1781 auto *exit = dyn_cast<BlockExit>(node);
1782 if (!exit)
1783 continue;
1784 // A slot is "partial" on the (exit, successor) edge if the reaching def
1785 // at the exit exists and has a usable condition, but doesn't flow into
1786 // that particular successor. Compute per flavor.
1787 for (bool delayed : {false, true}) {
1788 Def *def = exit->valueBefore->getReachingDef(delayed);
1789 if (!def || def->condition.isNever())
1790 continue;
1791 unsigned numContinues = 0;
1792 for (auto *successor : exit->successors)
1793 if (successor->valueAfter->getReachingDef(delayed))
1794 ++numContinues;
1795 if (numContinues == 0 || numContinues == exit->successors.size())
1796 continue;
1797 for (auto *successor : exit->successors)
1798 if (partialAt(exit->valueBefore, successor->valueAfter, delayed,
1799 exit->successors.size()))
1800 worklist.insert({exit, successor});
1801 }
1802 }
1803
1804 // Insert drive blocks before all blocks we have identified.
1805 for (auto [predecessor, successor] : worklist) {
1806 LLVM_DEBUG(llvm::dbgs() << "- Inserting drive block towards " << successor
1807 << " after " << *predecessor->terminator << "\n");
1808 OpBuilder builder(predecessor->terminator);
1809 auto *newBlock = builder.createBlock(successor->block);
1810 for (auto oldArg : successor->block->getArguments())
1811 newBlock->addArgument(oldArg.getType(), oldArg.getLoc());
1812 cf::BranchOp::create(builder, predecessor->terminator->getLoc(),
1813 successor->block, newBlock->getArguments());
1814 for (auto &blockOp : predecessor->terminator->getBlockOperands())
1815 if (blockOp.get() == successor->block)
1816 blockOp.set(newBlock);
1817
1818 // Create new nodes in the lattice for the added block. The new block
1819 // carries the same needed flag as its successor and the same reaching
1820 // defs as its predecessor.
1821 auto *value = lattice->createValue();
1822 value->needed = successor->valueAfter->needed;
1823 value->blockingReachingDef = predecessor->valueBefore->blockingReachingDef;
1824 value->delayedReachingDef = predecessor->valueBefore->delayedReachingDef;
1825 auto *newEntry = lattice->createNode<BlockEntry>(newBlock, value);
1826 auto *newExit = lattice->createNode<BlockExit>(newBlock, value);
1827 newEntry->predecessors.push_back(predecessor);
1828 newExit->successors.push_back(successor);
1829 llvm::replace(successor->predecessors, predecessor, newExit);
1830 llvm::replace(predecessor->successors, successor, newEntry);
1831 }
1832}
1833
1834/// Insert drives wherever a reaching definition can no longer propagate. This
1835/// is the before any suspensions and before operations that have unknown
1836/// effects on memory slots.
1837void Promoter::insertDrives() {
1838 for (auto *node : lattice->nodes) {
1839 if (auto *exit = dyn_cast<BlockExit>(node))
1840 insertDrives(exit);
1841 else if (auto *drive = dyn_cast<DriveNode>(node))
1842 insertDrives(drive);
1843 }
1844}
1845
1846/// Insert drives at block terminators for definitions that do not propagate
1847/// into successors.
1848void Promoter::insertDrives(BlockExit *node) {
1849 auto builder = OpBuilder::atBlockTerminator(node->block);
1850
1851 // Reuse the cached `llhd.constant_time` op for this block, or create one
1852 // before the terminator on first use. Cached across slots so we end up
1853 // with one constant-time op per block exit, not one per promoted slot.
1854 auto getDeltaTime = [&]() -> ConstantTimeOp {
1855 auto &cached = delayedTimeCache[node->block];
1856 if (!cached)
1857 cached = ConstantTimeOp::create(builder, node->terminator->getLoc(), 0,
1858 "ns", 1);
1859 return cached;
1860 };
1861
1862 auto insertDriveForSlot = [&](bool delayed) {
1863 Def *reachingDef = node->valueBefore->getReachingDef(delayed);
1864 if (!reachingDef || reachingDef->condition.isNever())
1865 return;
1866 if (!node->suspends && !node->successors.empty() &&
1867 llvm::all_of(node->successors, [&](auto *successor) {
1868 return successor->valueAfter->getReachingDef(delayed) != nullptr;
1869 }))
1870 return;
1871 LLVM_DEBUG(llvm::dbgs() << "- Inserting drive for " << currentSlot << " "
1872 << (delayed ? "(delayed)" : "(blocking)")
1873 << " before " << *node->terminator << "\n");
1874 auto value = reachingDef->getValueOrPlaceholder();
1875 auto enable = reachingDef->condition.isConditional()
1876 ? reachingDef->getConditionOrPlaceholder()
1877 : Value{};
1878 if (delayed)
1879 DriveOp::create(builder, currentSlot.getLoc(), currentSlot, value,
1880 getDeltaTime(), enable);
1881 else
1882 AssignOp::create(builder, currentSlot.getLoc(), currentSlot, value,
1883 enable);
1884 };
1885
1886 insertDriveForSlot(/*delayed=*/false);
1887 insertDriveForSlot(/*delayed=*/true);
1888}
1889
1890/// Remove drives to the current slot. These have been replaced with new
1891/// drives at block exits.
1892void Promoter::insertDrives(DriveNode *node) {
1893 LLVM_DEBUG(llvm::dbgs() << "- Removing drive " << *node->op << "\n");
1894 pruner.eraseNow(node->op);
1895 node->op = nullptr;
1896}
1897
1898//===----------------------------------------------------------------------===//
1899// Drive-to-Probe Forwarding
1900//===----------------------------------------------------------------------===//
1901
1902/// Forward definitions throughout the IR.
1903void Promoter::resolveDefinitions() {
1904 for (auto *node : lattice->nodes) {
1905 if (auto *probe = dyn_cast<ProbeNode>(node))
1906 resolveDefinitions(probe);
1907 else if (auto *drive = dyn_cast<DriveNode>(node))
1908 resolveDefinitions(drive);
1909 }
1910}
1911
1912/// Replace probes with the corresponding reaching definition.
1913void Promoter::resolveDefinitions(ProbeNode *node) {
1914 Def *def = node->valueBefore->blockingReachingDef;
1915 assert(def && "no definition reaches probe");
1916
1917 // Gather any projections between the probe and the underlying slot.
1918 auto projections = getProjections(node->op->getOperand(0), node->slot);
1919
1920 // Extract the projected value from the aggregate.
1921 auto builder = OpBuilder(node->op);
1922 auto value = def->getValueOrPlaceholder();
1923 value = unpackProjections(builder, value, projections);
1924
1925 // Replace the probe result with the projected value.
1926 LLVM_DEBUG(llvm::dbgs() << "- Replacing " << *node->op << " with " << value
1927 << "\n");
1928 replaceValueWith(node->op->getResult(0), value);
1929 pruner.eraseNow(node->op);
1930 node->op = nullptr;
1931}
1932
1933/// Mutate reaching definitions for conditional drives or drives that target
1934/// projections of a slot.
1935void Promoter::resolveDefinitions(DriveNode *node) {
1936 // Check whether the drive already has a value and condition set for its
1937 // reaching def. This is the case for drives to an entire slot. Conditional
1938 // drives and drives to a projection will have no value set initially, in
1939 // which case either the value is null or it is a placeholder.
1940 if (!node->def->value || node->def->valueIsPlaceholder)
1941 resolveDefinitionValue(node);
1942 if (node->def->condition.isConditional() &&
1943 (!node->def->condition.getCondition() ||
1944 node->def->conditionIsPlaceholder))
1945 resolveDefinitionCondition(node);
1946}
1947
1948void Promoter::resolveDefinitionValue(DriveNode *node) {
1949 // Get the slot definition reaching the drive. This is the value the drive has
1950 // to update.
1951 Def *inDef = node->valueBefore->getReachingDef(isDelayed(node->slot));
1952 assert(inDef && "no definition reaches drive");
1953 auto driveOp = node->getDriveOp();
1954 LLVM_DEBUG(llvm::dbgs() << "- Injecting value for " << driveOp << "\n");
1955
1956 // Gather any projections between the drive and the underlying slot.
1957 auto projections = getProjections(driveOp.getDriven(), getSlot(node->slot));
1958
1959 // Extract the current value from the aggregate.
1960 auto builder = OpBuilder(driveOp);
1961 auto value = inDef->getValueOrPlaceholder();
1962 value = unpackProjections(builder, value, projections);
1963
1964 // Update the value according to the drive.
1965 pruner.eraseLaterIfUnused(value);
1966 if (!driveOp.getEnable())
1967 value = driveOp.getValue();
1968 else
1969 value = builder.createOrFold<comb::MuxOp>(
1970 driveOp.getLoc(), driveOp.getEnable(), driveOp.getValue(), value);
1971
1972 // Inject the updated value into the aggregate.
1973 value = packProjections(builder, value, projections);
1974
1975 // Track the updated slot value in the drive's reaching def.
1976 if (node->def->valueIsPlaceholder) {
1977 auto *placeholder = node->def->value.getDefiningOp();
1978 assert(isa_and_nonnull<UnrealizedConversionCastOp>(placeholder) &&
1979 "placeholder replaced but valueIsPlaceholder still set");
1980 replaceValueWith(placeholder->getResult(0), value);
1981 pruner.eraseNow(placeholder);
1982 node->def->valueIsPlaceholder = false;
1983 }
1984 node->def->value = value;
1985}
1986
1987void Promoter::resolveDefinitionCondition(DriveNode *node) {
1988 // Get the slot definition reaching the drive. This contains the condition the
1989 // drive has to update.
1990 Def *inDef = node->valueBefore->getReachingDef(isDelayed(node->slot));
1991 assert(inDef && "no definition reaches drive");
1992 auto driveOp = node->getDriveOp();
1993 LLVM_DEBUG(llvm::dbgs() << "- Mutating condition for " << driveOp << "\n");
1994 OpBuilder builder(driveOp);
1995
1996 // Adjust the drive condition by combining the incoming condition with the
1997 // enable of this drive op.
1998 Value condition;
1999 if (inDef->condition.isNever())
2000 condition = driveOp.getEnable();
2001 else
2002 condition =
2003 builder.createOrFold<comb::OrOp>(driveOp.getLoc(), driveOp.getEnable(),
2004 inDef->getConditionOrPlaceholder());
2005
2006 // Track the updated drive condition in the drive's reaching def.
2007 if (node->def->conditionIsPlaceholder) {
2008 auto *placeholder = node->def->condition.getCondition().getDefiningOp();
2009 assert(isa_and_nonnull<UnrealizedConversionCastOp>(placeholder) &&
2010 "placeholder replaced but conditionIsPlaceholder still set");
2011 replaceValueWith(placeholder->getResult(0), condition);
2012 pruner.eraseNow(placeholder);
2013 node->def->conditionIsPlaceholder = false;
2014 }
2015 node->def->condition.setCondition(condition);
2016}
2017
2018//===----------------------------------------------------------------------===//
2019// Block Argument Insertion
2020//===----------------------------------------------------------------------===//
2021
2022/// Insert block arguments into the IR.
2023void Promoter::insertBlockArgs() {
2024 bool anyArgsInserted = true;
2025 while (anyArgsInserted) {
2026 anyArgsInserted = false;
2027 for (auto *node : lattice->nodes)
2028 if (auto *entry = dyn_cast<BlockEntry>(node))
2029 anyArgsInserted |= insertBlockArgs(entry);
2030 }
2031}
2032
2033/// Insert block arguments for any merging definitions for which a placeholder
2034/// value has been created. Also insert corresponding successor operands to any
2035/// ops branching here. Returns true if any arguments were inserted.
2036///
2037/// This function may create additional placeholders in predecessor blocks.
2038/// Creating block arguments in a later block may uncover additional arguments
2039/// to be inserted in a previous one. Therefore this function must be called
2040/// until no more block arguments are inserted.
2041bool Promoter::insertBlockArgs(BlockEntry *node) {
2042 // Determine which merge defs for the current slot still have unresolved
2043 // placeholders. Check the blocking flavor first, then the delayed flavor,
2044 // so block argument ordering is deterministic per slot (and the
2045 // slot-iteration order in promote() gives deterministic ordering across
2046 // slots).
2047 enum class Which { Value, Condition };
2048 SmallVector<std::pair<DefSlot, Which>> neededSlots;
2049 auto addNeededSlot = [&](DefSlot slot) {
2050 auto *def = node->getMerged(isDelayed(slot));
2051 if (!def)
2052 return;
2053 if (!node->valueAfter->getReachingDef(isDelayed(slot)))
2054 return;
2055 if (def->valueIsPlaceholder)
2056 neededSlots.push_back({slot, Which::Value});
2057 if (def->conditionIsPlaceholder)
2058 neededSlots.push_back({slot, Which::Condition});
2059 };
2060 addNeededSlot(blockingSlot(currentSlot));
2061 addNeededSlot(delayedSlot(currentSlot));
2062 if (neededSlots.empty())
2063 return false;
2064 LLVM_DEBUG(llvm::dbgs() << "- Adding " << neededSlots.size()
2065 << " args to block " << node->block << "\n");
2066
2067 // Add the block arguments.
2068 for (auto [slot, which] : neededSlots) {
2069 auto *def = node->getMerged(isDelayed(slot));
2070 assert(def);
2071 switch (which) {
2072 case Which::Value: {
2073 // Create an argument for the definition's value and replace any
2074 // placeholder we might have created earlier.
2075 auto *placeholder = def->value.getDefiningOp();
2076 assert(isa_and_nonnull<UnrealizedConversionCastOp>(placeholder) &&
2077 "placeholder replaced but valueIsPlaceholder still set");
2078 auto arg = node->block->addArgument(getStoredType(slot), getLoc(slot));
2079 replaceValueWith(placeholder->getResult(0), arg);
2080 pruner.eraseNow(placeholder);
2081 def->value = arg;
2082 def->valueIsPlaceholder = false;
2083 break;
2084 }
2085 case Which::Condition: {
2086 // If the definition's drive mode is conditional, create an argument for
2087 // the drive condition and replace any placeholder we might have created
2088 // earlier.
2089 auto *placeholder = def->condition.getCondition().getDefiningOp();
2090 assert(isa_and_nonnull<UnrealizedConversionCastOp>(placeholder) &&
2091 "placeholder replaced but conditionIsPlaceholder still set");
2092 auto conditionArg = node->block->addArgument(
2093 IntegerType::get(region.getContext(), 1), getLoc(slot));
2094 replaceValueWith(placeholder->getResult(0), conditionArg);
2095 pruner.eraseNow(placeholder);
2096 def->condition.setCondition(conditionArg);
2097 def->conditionIsPlaceholder = false;
2098 break;
2099 }
2100 }
2101 }
2102
2103 // Add successor operands to the predecessor terminators.
2104 SmallPtrSet<BlockExit *, 4> updatedPredecessors;
2105 for (auto *predecessor : node->predecessors) {
2106 // A single terminator can have multiple CFG edges to the same block, for
2107 // example a `cf.cond_br` whose true and false destinations are identical
2108 // but carry different values. The lattice records one predecessor entry
2109 // per edge, while the terminator update below walks and updates every edge
2110 // to `node->block`. Updating the same terminator once per edge would
2111 // append duplicate operands to each successor edge without adding matching
2112 // block arguments.
2113 if (!updatedPredecessors.insert(predecessor).second)
2114 continue;
2115
2116 // Collect the interesting reaching definitions in the predecessor.
2117 SmallVector<Value> args;
2118 for (auto [slot, which] : neededSlots) {
2119 Def *def = predecessor->valueBefore->getReachingDef(isDelayed(slot));
2120 auto builder = OpBuilder::atBlockTerminator(predecessor->block);
2121 switch (which) {
2122 case Which::Value:
2123 if (def) {
2124 args.push_back(def->getValueOrPlaceholder());
2125 } else {
2126 auto type = getStoredType(slot);
2127 args.push_back(createZeroValue(builder, getLoc(slot), type));
2128 }
2129 break;
2130 case Which::Condition:
2131 if (def) {
2132 args.push_back(def->getConditionOrPlaceholder());
2133 } else {
2134 args.push_back(hw::ConstantOp::create(builder, getLoc(slot),
2135 builder.getI1Type(), 0));
2136 }
2137 break;
2138 }
2139 }
2140
2141 // Add the reaching definitions to the predecessor edge. `llhd.wait` is a
2142 // suspending terminator with successor operands, but it does not implement
2143 // BranchOpInterface.
2144 if (auto branchOp = dyn_cast<BranchOpInterface>(predecessor->terminator)) {
2145 SmallVector<unsigned> successorOperandNumbers;
2146 for (auto &blockOperand : branchOp->getBlockOperands())
2147 if (blockOperand.get() == node->block)
2148 successorOperandNumbers.push_back(blockOperand.getOperandNumber());
2149 for (auto operandNumber : successorOperandNumbers)
2150 branchOp.getSuccessorOperands(operandNumber).append(args);
2151 continue;
2152 }
2153 if (auto waitOp = dyn_cast<WaitOp>(predecessor->terminator)) {
2154 if (waitOp.getDest() == node->block)
2155 waitOp.getDestOperandsMutable().append(args);
2156 continue;
2157 }
2158 llvm_unreachable(
2159 "mem2reg predecessor terminator has no successor operands");
2160 }
2161
2162 return true;
2163}
2164
2165/// Replace all uses of an old value with a new value in the IR, and update all
2166/// mentions of the old value in the lattice to the new value.
2167void Promoter::replaceValueWith(Value oldValue, Value newValue) {
2168 oldValue.replaceAllUsesWith(newValue);
2169 for (auto *def : lattice->defs) {
2170 if (def->value == oldValue)
2171 def->value = newValue;
2172 if (def->condition.isConditional() &&
2173 def->condition.getCondition() == oldValue)
2174 def->condition.setCondition(newValue);
2175 }
2176}
2177
2178//===----------------------------------------------------------------------===//
2179// Cleanup
2180//===----------------------------------------------------------------------===//
2181
2182/// Remove a local signal if it is only used by projection ops and drives, but
2183/// never probed. Since the signal is local and cannot be observed in any other
2184/// way, we can safely remove it along with any projection ops and drives.
2185void Promoter::removeUnusedLocalSignal(SignalOp signalOp) {
2186 // Check if the signal is only ever projected into and driven, but never
2187 // probed.
2188 SmallSetVector<Operation *, 8> users;
2189 SmallVector<Operation *> worklist;
2190 worklist.push_back(signalOp);
2191 while (!worklist.empty()) {
2192 auto *op = worklist.pop_back_val();
2193 if (!isa<SignalOp, DriveLikeOp, SigArrayGetOp, SigArraySliceOp,
2194 SigExtractOp, SigStructExtractOp>(op))
2195 return;
2196 for (auto *user : op->getUsers())
2197 if (users.insert(user))
2198 worklist.push_back(user);
2199 }
2200
2201 // If we get here, the local signal is never probed. This means we can safely
2202 // remove it.
2203 LLVM_DEBUG(llvm::dbgs() << "- Removing local signal " << *signalOp << "\n");
2204 for (auto *op : llvm::reverse(users))
2205 pruner.eraseNow(op);
2206}
2207
2208//===----------------------------------------------------------------------===//
2209// Pass Infrastructure
2210//===----------------------------------------------------------------------===//
2211
2212namespace {
2213struct Mem2RegPass : public llhd::impl::Mem2RegPassBase<Mem2RegPass> {
2214 void runOnOperation() override;
2215};
2216} // namespace
2217
2218void Mem2RegPass::runOnOperation() {
2219 SmallVector<Region *> regions;
2220 getOperation()->walk<WalkOrder::PreOrder>([&](Operation *op) {
2221 if (isa<ProcessOp, FinalOp, CombinationalOp, CoroutineOp>(op)) {
2222 auto &region = op->getRegion(0);
2223 if (!region.empty())
2224 regions.push_back(&region);
2225 return WalkResult::skip();
2226 }
2227 return WalkResult::advance();
2228 });
2229 for (auto *region : regions)
2230 if (failed(Promoter(*region).promote()))
2231 return signalPassFailure();
2232}
static bool isAlways(Attribute attr, bool expected)
Definition ArcFolds.cpp:21
assert(baseType &&"element must be base type")
static void dump(DIModule &module, raw_indented_ostream &os)
static Value createZeroValue(ImplicitLocOpBuilder &builder, FIRRTLBaseType type, SmallDenseMap< FIRRTLBaseType, Value > &cache)
Construct a zero value of the given type using the given builder.
static std::optional< unsigned > getPromotableSlotBitWidth(Type type)
Definition Mem2Reg.cpp:195
static bool isDelayed(DefSlot slot)
Definition Mem2Reg.cpp:189
static bool isPromotableSlotType(Type type)
Definition Mem2Reg.cpp:207
static Value packProjections(OpBuilder &builder, Value value, const ProjectionStack &projections)
Undo a stack of projections by taking the value of the projected field and injecting it into the surr...
Definition Mem2Reg.cpp:668
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:193
static ProjectionStack getProjections(Value fromSignal, Value toSlot)
Collect the llhd.sig.
Definition Mem2Reg.cpp:612
static bool isDeltaDrive(const Operation *op)
Check whether an operation is a llhd.drv with a delta delay.
Definition Mem2Reg.cpp:47
static DefSlot blockingSlot(Value slot)
Definition Mem2Reg.cpp:186
static Value unpackProjections(OpBuilder &builder, Value value, ProjectionStack &projections)
Resolve a stack of projections by taking a value and descending into its subelements until the final ...
Definition Mem2Reg.cpp:628
static bool isBlockingDrive(const Operation *op)
Check whether an operation is an llhd.assign.
Definition Mem2Reg.cpp:43
static DefSlot delayedSlot(Value slot)
Definition Mem2Reg.cpp:187
static Value getSlot(DefSlot slot)
Definition Mem2Reg.cpp:188
static Type getStoredType(DefSlot slot)
Definition Mem2Reg.cpp:190
SmallVector< Projection > ProjectionStack
A stack of projection operations.
Definition Mem2Reg.cpp:605
PointerIntPair< Value, 1 > DefSlot
The slot a reaching definition specifies a value for, alongside a bit indicating whether the definiti...
Definition Mem2Reg.cpp:185
return success()
create(data_type, value)
Definition hw.py:444
create(data_type, value)
Definition hw.py:433
Value createDynamicInject(OpBuilder &builder, Location loc, Value value, Value offset, Value replacement, bool twoState=false)
Replace a range of bits in an integer at a dynamic offset, and return the updated integer value.
Definition CombOps.cpp:198
Value createDynamicExtract(OpBuilder &builder, Location loc, Value value, Value offset, unsigned width)
Extract a range of bits from an integer at a dynamic offset.
Definition CombOps.cpp:178
static bool operator==(const ModulePort &a, const ModulePort &b)
Definition HWTypes.h:64
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:122
std::optional< ProjectionRange > getProjectionRange(Operation *op)
Calculate a projection's range.
std::variant< ConstProjectionRange, DynProjectionRange > ProjectionRange
Portion of the signal operand that is selected by a projection.
void captureAcrossWait(Value value, ArrayRef< WaitOp > waitOps, mlir::Liveness &liveness, mlir::DominanceInfo &dominance)
Add a value as block argument to a list of wait ops and update uses of the value to use the added blo...
Operation * getRootSignal(Value sig)
Given a signal or a projection, walk back the projection chain until you find the root signal declara...
bool isProjection(const Operation *op)
Check if an op is one of the supported projection types.
bool isDynamic(const ProjectionRange &range)
Helper to check if a projection range is dynamic or not.
bool isProvablyDisjoint(const ProjectionRange &a, const ProjectionRange &b)
Check whether two projections provably describe disjoint storage.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
bool operator!=(uint64_t a, const FVInt &b)
Definition FVInt.h:685
void eraseLaterIfUnused(Operation *op)
Mark an op the be erased later if it is unused at that point.
void eraseNow(Operation *op)
Erase an operation immediately, and remove it from the set of ops to be removed later.
static bool isEqual(DriveCondition lhs, DriveCondition rhs)
Definition Mem2Reg.cpp:173
static unsigned getHashValue(DriveCondition d)
Definition Mem2Reg.cpp:169