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"
23#define DEBUG_TYPE "llhd-mem2reg"
27#define GEN_PASS_DEF_MEM2REGPASS
28#include "circt/Dialect/LLHD/LLHDPasses.h.inc"
36using llvm::PointerIntPair;
37using llvm::SmallDenseSet;
39using llvm::SpecificBumpPtrAllocator;
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;
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);
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;
79 Value getCondition()
const {
return conditionAndMode.getPointer(); }
80 void setCondition(Value condition) { conditionAndMode.setPointer(condition); }
82 bool operator==(
const DriveCondition &other)
const {
83 return conditionAndMode == other.conditionAndMode;
85 bool operator!=(
const DriveCondition &other)
const {
86 return conditionAndMode != other.conditionAndMode;
95 typedef PointerIntPair<Value, 2> ConditionAndMode;
96 ConditionAndMode conditionAndMode;
98 DriveCondition(ConditionAndMode conditionAndMode)
99 : conditionAndMode(conditionAndMode) {}
100 friend DenseMapInfo<DriveCondition>;
112 DriveCondition condition;
113 bool valueIsPlaceholder =
false;
114 bool conditionIsPlaceholder =
false;
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) {}
122 Value getValueOrPlaceholder();
123 Value getConditionOrPlaceholder();
129Value Def::getValueOrPlaceholder() {
131 auto builder = OpBuilder::atBlockBegin(block);
132 value = UnrealizedConversionCastOp::create(builder, builder.getUnknownLoc(),
135 valueIsPlaceholder =
true;
144Value Def::getConditionOrPlaceholder() {
145 if (!condition.getCondition()) {
146 auto builder = OpBuilder::atBlockBegin(block);
148 if (condition.isNever()) {
150 builder.getI1Type(), 0);
151 }
else if (condition.isAlways()) {
153 builder.getI1Type(), 1);
156 UnrealizedConversionCastOp::create(builder, builder.getUnknownLoc(),
157 builder.getI1Type(), ValueRange{})
159 conditionIsPlaceholder =
true;
161 condition.setCondition(value);
163 return condition.getCondition();
173 static bool isEqual(DriveCondition lhs, DriveCondition rhs) {
196 if (
auto intTy = dyn_cast<IntegerType>(type))
197 return intTy.getWidth();
198 if (
auto floatTy = dyn_cast<FloatType>(type))
199 return floatTy.getWidth();
204 return static_cast<unsigned>(bitWidth);
209 return bitWidth && *bitWidth <= IntegerType::kMaxWidth;
213 if (isa<FloatType>(type))
214 return arith::ConstantOp::create(builder, loc, builder.getZeroAttr(type));
217 assert(bitWidth &&
"cannot create zero value for unpromotable slot type");
218 auto flatType = builder.getIntegerType(*bitWidth);
220 if (type != flatType)
241 LatticeNode *nodeBefore =
nullptr;
242 LatticeNode *nodeAfter =
nullptr;
244 Def *blockingReachingDef =
nullptr;
245 Def *delayedReachingDef =
nullptr;
248 Def *getReachingDef(
bool delayed)
const {
249 return delayed ? delayedReachingDef : blockingReachingDef;
251 void setReachingDef(
bool delayed, Def *def) {
252 (delayed ? delayedReachingDef : blockingReachingDef) = def;
257 enum class Kind { BlockEntry, BlockExit, Probe, Drive, Slot };
261 LatticeNode(Kind kind) : kind(kind) {}
264struct BlockEntry :
public LatticeNode {
266 LatticeValue *valueAfter;
267 SmallVector<BlockExit *, 2> predecessors;
271 Def *insertedProbe =
nullptr;
274 Def *blockingMerged =
nullptr;
275 Def *delayedMerged =
nullptr;
277 BlockEntry(Block *block, LatticeValue *valueAfter)
278 : LatticeNode(Kind::BlockEntry), block(block), valueAfter(valueAfter) {
279 assert(!valueAfter->nodeBefore);
280 valueAfter->nodeBefore =
this;
283 Def *getMerged(
bool delayed)
const {
284 return delayed ? delayedMerged : blockingMerged;
286 void setMerged(
bool delayed, Def *def) {
287 (delayed ? delayedMerged : blockingMerged) = def;
290 static bool classof(
const LatticeNode *n) {
291 return n->kind == Kind::BlockEntry;
295struct BlockExit :
public LatticeNode {
297 LatticeValue *valueBefore;
298 SmallVector<BlockEntry *, 2> successors;
299 Operation *terminator;
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;
310 static bool classof(
const LatticeNode *n) {
311 return n->kind == Kind::BlockExit;
315struct OpNode :
public LatticeNode {
317 LatticeValue *valueBefore;
318 LatticeValue *valueAfter;
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;
330 static bool classof(
const LatticeNode *n) {
331 return isa<ProbeNode, DriveNode, SlotNode>(n);
335struct ProbeNode :
public OpNode {
338 ProbeNode(ProbeOp op, Value slot, LatticeValue *valueBefore,
339 LatticeValue *valueAfter)
340 : OpNode(Kind::Probe, op, valueBefore, valueAfter), slot(slot) {}
342 static bool classof(
const LatticeNode *n) {
return n->kind == Kind::Probe; }
345struct DriveNode :
public OpNode {
349 DriveNode(DriveLikeOp op, Value slot, Def *def, LatticeValue *valueBefore,
350 LatticeValue *valueAfter)
351 : OpNode(Kind::Drive, op, valueBefore, valueAfter),
359 bool drivesProjection()
const {
return op->getOperand(0) !=
getSlot(slot); }
362 DriveLikeOp getDriveOp()
const {
return cast<DriveLikeOp>(op); }
364 static bool classof(
const LatticeNode *n) {
return n->kind == Kind::Drive; }
367struct SlotNode :
public OpNode {
372 SlotNode(Operation *op, Def *def, LatticeValue *valueBefore,
373 LatticeValue *valueAfter)
374 : OpNode(Kind::Slot, op, valueBefore, valueAfter), def(def) {}
376 bool isSignal()
const {
return isa<SignalOp>(op); }
379 static bool classof(
const LatticeNode *n) {
return n->kind == Kind::Slot; }
386 LatticeValue *createValue() {
387 auto *value =
new (valueAllocator.Allocate()) LatticeValue();
388 values.push_back(value);
393 template <
class T,
typename... Args>
394 T *createNode(Args... args) {
396 new (getAllocator<T>().Allocate()) T(std::forward<Args>(args)...);
397 nodes.push_back(node);
402 template <
typename... Args>
403 Def *createDef(Args... args) {
404 auto *def =
new (defAllocator.Allocate()) Def(std::forward<Args>(args)...);
410 Def *createDef(Value value, DriveCondition mode) {
411 auto &slot = defsForValues[{value, mode}];
413 slot =
new (defAllocator.Allocate()) Def(value, mode);
414 defs.push_back(slot);
420 void dump(llvm::raw_ostream &os = llvm::dbgs());
424 std::vector<LatticeNode *> nodes;
426 std::vector<LatticeValue *> values;
428 std::vector<Def *> defs;
432 DenseMap<std::pair<Value, DriveCondition>, Def *> defsForValues;
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;
445 SpecificBumpPtrAllocator<T> &getAllocator();
451SpecificBumpPtrAllocator<BlockEntry> &Lattice::getAllocator() {
452 return blockEntryAllocator;
455SpecificBumpPtrAllocator<BlockExit> &Lattice::getAllocator() {
456 return blockExitAllocator;
459SpecificBumpPtrAllocator<ProbeNode> &Lattice::getAllocator() {
460 return probeAllocator;
463SpecificBumpPtrAllocator<DriveNode> &Lattice::getAllocator() {
464 return driveAllocator;
467SpecificBumpPtrAllocator<SlotNode> &Lattice::getAllocator() {
468 return slotAllocator;
475void Lattice::dump(llvm::raw_ostream &os) {
477 llvm::MapVector<Block *, unsigned> blockNames;
478 llvm::MapVector<Value, unsigned> memNames;
479 llvm::MapVector<Def *, unsigned> defNames;
481 auto blockName = [&](
Block *block) {
482 unsigned id = blockNames.insert({block, blockNames.size()}).first->second;
483 return std::string(
"bb") + llvm::utostr(
id);
486 auto memName = [&](
DefSlot value) {
488 memNames.insert({
getSlot(value), memNames.size()}).first->second;
489 return std::string(
"mem") + llvm::utostr(
id) +
493 auto defName = [&](Def *def) {
494 unsigned id = defNames.insert({def, defNames.size()}).first->second;
495 return std::string(
"def") + llvm::utostr(
id);
499 for (
auto *node : nodes)
500 if (
auto *entry = dyn_cast<BlockEntry>(node))
501 blockName(entry->block);
505 for (
auto *node : nodes) {
506 auto *entry = dyn_cast<BlockEntry>(node);
511 os <<
" " << blockName(entry->block) <<
":";
512 if (entry->predecessors.empty()) {
513 os <<
" // no predecessors";
516 for (
auto *node : entry->predecessors)
517 os <<
" " << blockName(node->block);
522 auto *value = entry->valueAfter;
527 auto printDef = [&](
bool delayed, Def *def) {
530 os <<
" -> def (" << (delayed ?
"delayed" :
"blocking")
531 <<
")=" << defName(def);
532 if (def->condition.isNever())
534 else if (def->condition.isAlways())
540 printDef(
false, value->blockingReachingDef);
541 printDef(
true, value->delayedReachingDef);
542 if (isa<BlockExit>(value->nodeAfter))
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";
556 value = cast<OpNode>(value->nodeAfter)->valueAfter;
560 auto *exit = cast<BlockExit>(value->nodeAfter);
561 if (isa<WaitOp>(exit->terminator))
563 else if (exit->successors.empty())
567 for (
auto *node : exit->successors)
568 os <<
" " << blockName(node->block);
570 os <<
" // suspends";
575 for (
auto [mem,
id] : memNames)
576 os <<
" mem" <<
id <<
": " << mem <<
"\n";
614 while (fromSignal != toSlot) {
615 auto *op = cast<OpResult>(fromSignal).getOwner();
616 stack.push_back({op, Value(), {}});
617 fromSignal = op->getOperand(0);
630 for (
auto &projection : llvm::reverse(projections)) {
631 projection.into = value;
632 value = TypeSwitch<Operation *, Value>(projection.op)
633 .Case<SigArrayGetOp>([&](
auto op) {
635 op.getLoc(), value, op.getIndex());
637 .Case<SigStructExtractOp>([&](
auto op) {
640 if (isa<hw::UnionType>(value.getType()))
641 return builder.createOrFold<hw::UnionExtractOp>(
642 op.getLoc(), value, op.getFieldAttr());
644 op.getLoc(), value, op.getFieldAttr());
646 .Case<SigExtractOp>([&](
auto op) {
647 auto type = cast<RefType>(op.getType()).getNestedType();
648 auto width = type.getIntOrFloatBitWidth();
650 op.getLowBit(), width);
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);
676 .Case<SigStructExtractOp>([&](
auto op) {
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);
686 .Case<SigExtractOp>([&](
auto op) {
689 op.getLowBit(), value);
704struct PromotionTree {
706 using Access = Operation *;
711 Node(Operation *op) : op(op) {}
715 return llvm::concat<Access>(directAccesses, foldedAccesses);
717 bool hasInRegionAccess(
const Region ®ion) {
718 return llvm::any_of(accesses(), [&](Access &access) {
719 return access && access->getParentRegion() == ®ion;
722 bool hasInRegionDeltaDrive(
const Region ®ion) {
723 return llvm::any_of(accesses(), [&](Access &access) {
724 return access->getParentRegion() == ®ion &&
isDeltaDrive(access);
727 bool hasInRegionBlockingDrive(
const Region ®ion) {
728 return llvm::any_of(accesses(), [&](Access &access) {
729 return access->getParentRegion() == ®ion &&
isBlockingDrive(access);
732 bool hasInRegionDrive(
const Region ®ion) {
733 return llvm::any_of(accesses(), [&](Access &access) {
734 return access->getParentRegion() == ®ion && isa<DriveLikeOp>(access);
737 bool hasInRegionProjectedDrive(
const Region ®ion) {
738 return llvm::any_of(foldedAccesses, [&](Access &access) {
739 return access->getParentRegion() == ®ion && isa<DriveLikeOp>(access);
742 bool hasProjection()
const {
return !foldedProjections.empty(); }
747 SmallVector<Access> directAccesses;
754 SmallVector<Access> foldedAccesses;
757 SmallVector<Operation *> foldedProjections;
771 Node *buildFrom(Operation *signal, Region ®ion);
773 Node *makeNode(Operation *op) {
774 nodes.emplace_back(std::make_unique<Node>(op));
775 return nodes.back().get();
779 SmallVector<std::unique_ptr<Node>, 8> nodes;
782PromotionTree::Node *PromotionTree::buildFrom(Operation *signal,
785 assert(isa<SignalOp>(signal));
786 Node *rootNode = makeNode(signal);
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();
795 SmallVector<Access, 4> accesses;
796 SmallVector<Projection, 4> projections;
797 for (Operation *user : curOp->getUsers()) {
799 if (region.isProperAncestor(user->getParentRegion()))
802 bool inRegion = user->getParentRegion() == ®ion;
804 if (isa<ProbeOp>(user)) {
806 curNode->isSlot |= inRegion;
807 accesses.push_back(user);
808 }
else if (isa<DriveLikeOp>(user)) {
813 curNode->isSlot |= inRegion;
814 accesses.push_back(user);
815 }
else if (isa<SigExtractOp, SigArrayGetOp, SigStructExtractOp>(user)) {
823 projections.push_back({user, user->getResult(0), *range});
833 if (!curNode->isSlot) {
834 auto overlaps = [&](
const Projection &p1,
const Projection &p2) {
837 curNode->isSlot |= llvm::any_of(projections, [&](Projection &proj) {
838 return llvm::any_of(projections, [&](Projection &sibling) {
839 return overlaps(proj, sibling);
845 if (relativePath.size() == 0)
846 curNode->directAccesses.append(accesses);
848 curNode->foldedAccesses.append(accesses);
851 for (
auto &proj : projections) {
852 if (curNode->isSlot) {
854 curNode->foldedProjections.push_back(proj.op);
856 auto path = relativePath;
857 path.push_back(proj);
858 worklist.push_back({proj.op, curNode, path});
861 auto *projNode = makeNode(proj.op);
864 worklist.push_back({proj.op, projNode, {}});
880 Promoter(Region ®ion) : region(region) {}
881 LogicalResult promote();
883 void findPromotableSlots();
884 Value resolveSlot(Value projectionOrSlot);
885 void populateSlotOps();
887 void computeLiveOutWait();
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);
899 void insertProbeBlocks();
901 void insertProbes(BlockEntry *node);
902 void insertProbes(SlotNode *node);
903 void hoistSlot(Operation *slotOp);
905 void insertDriveBlocks();
907 void insertDrives(BlockExit *node);
908 void insertDrives(DriveNode *node);
910 void resolveDefinitions();
911 void resolveDefinitions(ProbeNode *node);
912 void resolveDefinitions(DriveNode *node);
913 void resolveDefinitionValue(DriveNode *node);
914 void resolveDefinitionCondition(DriveNode *node);
916 void insertBlockArgs();
917 bool insertBlockArgs(BlockEntry *node);
918 void replaceValueWith(Value oldValue, Value newValue);
922 void removeUnusedLocalSignal(SignalOp signalOp);
931 SmallVector<WaitOp> waitOps;
933 llvm::SetVector<Value> liveOutWait;
935 std::unique_ptr<DominanceInfo> dominance;
936 std::unique_ptr<Liveness> liveness;
941 SmallVector<Value> slots;
943 SmallDenseMap<Value, Value> projections;
946 SmallDenseSet<Value> promotable;
955 DenseMap<Block *, ConstantTimeOp> delayedTimeCache;
960 std::optional<Lattice> lattice;
962 SmallVector<LatticeNode *> dirtyNodes;
965 UnusedOpPruner pruner;
969 DenseMap<Value, SmallVector<Operation *>> slotOps;
971 SmallSetVector<Operation *, 4> localSignals;
975LogicalResult Promoter::promote() {
979 computeLiveOutWait();
980 findPromotableSlots();
995 for (
auto slot : slots) {
1002 for (
auto *signalOp : localSignals)
1003 removeUnusedLocalSignal(cast<SignalOp>(signalOp));
1012void Promoter::promoteSlot() {
1013 assert(currentSlot &&
"currentSlot must be set before promoteSlot()");
1017 LLVM_DEBUG(llvm::dbgs() <<
"Promoting slot " << currentSlot <<
"\n");
1021 llvm::dbgs() <<
"Initial lattice:\n";
1026 propagateBackward();
1028 llvm::dbgs() <<
"After backward propagation:\n";
1033 insertProbeBlocks();
1036 llvm::dbgs() <<
"After probe insertion:\n";
1043 llvm::dbgs() <<
"After forward propagation:\n";
1048 resolveDefinitions();
1051 insertDriveBlocks();
1054 llvm::dbgs() <<
"After def resolution and drive insertion:\n";
1064 if (signalOp->getParentRegion() == ®ion)
1065 localSignals.insert(signalOp);
1073void Promoter::findPromotableSlots() {
1074 SmallPtrSet<Value, 8> seenSlots;
1075 SmallPtrSet<Operation *, 8> seenSignals;
1078 PromotionTree ptree;
1079 region.walk([&](Operation *op) {
1080 for (
auto operand : op->getOperands()) {
1081 if (!seenSlots.insert(operand).second)
1089 if (!seenSignals.insert(root).second)
1092 unsigned prevSize = ptree.nodes.size();
1093 auto *rootNode = ptree.buildFrom(root, region);
1096 ptree.nodes.pop_back_n(ptree.nodes.size() - prevSize);
1102 for (
auto &node : ptree.nodes) {
1104 if (!node->isSlot || !node->hasInRegionAccess(region))
1110 if (node->hasProjection() && node->hasInRegionBlockingDrive(region) &&
1111 node->hasInRegionDeltaDrive(region))
1116 Value slotVal = node->op->getResult(0);
1124 if (llvm::any_of(node->foldedProjections, [&](Operation *proj) {
1125 return liveOutWait.contains(proj->getOperand(0));
1130 slots.push_back(slotVal);
1131 for (
auto *proj : node->foldedProjections)
1132 projections[proj->getResult(0)] = slotVal;
1135 promotable.insert(slots.begin(), slots.end());
1136 projections.remove_if([&](
auto elem) {
1137 auto [projection, slot] = elem;
1138 return !promotable.contains(slot);
1140 for (
auto [projection, slot] : projections)
1141 promotable.insert(projection);
1143 LLVM_DEBUG(llvm::dbgs() <<
"Found " << slots.size() <<
" promotable slots, "
1144 << promotable.size() <<
" promotable values\n");
1149Value Promoter::resolveSlot(Value projectionOrSlot) {
1150 if (
auto slot = projections.lookup(projectionOrSlot))
1152 return projectionOrSlot;
1158void Promoter::computeLiveOutWait() {
1159 if (region.hasOneBlock())
1162 for (
auto &block : region)
1163 if (
auto waitOp = dyn_cast<WaitOp>(block.getTerminator()))
1164 waitOps.push_back(waitOp);
1166 if (waitOps.empty())
1169 dominance = std::make_unique<DominanceInfo>(region.getParentOp());
1170 liveness = std::make_unique<Liveness>(region.getParentOp());
1172 auto isDefinedInRegion = [&](Value v) {
1173 return v.getParentRegion() == ®ion;
1176 for (
auto waitOp : waitOps) {
1177 Block *waitBlock = waitOp->getBlock();
1178 const auto &liveOutValues = liveness->getLiveOut(waitBlock);
1180 for (Value v : liveOutValues) {
1181 if (!isDefinedInRegion(v))
1183 liveOutWait.insert(v);
1192void Promoter::captureAcrossWait() {
1193 if (!dominance || !liveness)
1195 for (Value v : liveOutWait)
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());
1216 .Case([&](DriveLikeOp op) {
1217 if (promotable.contains(op.getDriven()))
1218 return resolveSlot(op.getDriven());
1221 .Case<SigExtractOp, SigArrayGetOp, SigStructExtractOp>(
1222 [&](Operation *op) -> Value {
1223 if (llvm::is_contained(slots, op->getResult(0)))
1224 return op->getResult(0);
1227 .Case([&](SignalOp op) {
return op.getResult(); })
1228 .Default([&](Operation *) {
return Value(); });
1230 slotOps[slot].push_back(&op);
1239void Promoter::constructLattice() {
1240 assert(currentSlot &&
"constructLattice requires currentSlot");
1244 ArrayRef<Operation *> currentSlotOps = slotOps[currentSlot];
1247 SmallDenseMap<Block *, BlockEntry *, 8> blockEntries;
1248 for (
auto &block : region) {
1250 lattice->createNode<BlockEntry>(&block, lattice->createValue());
1251 blockEntries.insert({&block, entry});
1255 for (
auto &block : region) {
1256 auto *valueBefore = blockEntries.lookup(&block)->valueAfter;
1260 ArrayRef<Operation *> blockOps = currentSlotOps.take_while(
1261 [&](Operation *op) {
return op->getBlock() == █ });
1262 currentSlotOps = currentSlotOps.drop_front(blockOps.size());
1264 for (Operation *op : blockOps) {
1266 if (
auto probeOp = dyn_cast<ProbeOp>(op)) {
1267 if (!promotable.contains(probeOp.getSignal()))
1269 if (resolveSlot(probeOp.getSignal()) != currentSlot)
1271 auto *node = lattice->createNode<ProbeNode>(
1272 probeOp, currentSlot, valueBefore, lattice->createValue());
1273 valueBefore = node->valueAfter;
1278 if (
auto driveOp = dyn_cast<DriveLikeOp>(op)) {
1281 auto signal = driveOp.getDriven();
1282 if (!promotable.contains(signal))
1284 if (resolveSlot(signal) != currentSlot)
1286 auto condition = DriveCondition::always();
1287 if (
auto enable = driveOp.getEnable())
1288 condition = DriveCondition::conditional(enable);
1293 signal == currentSlot
1294 ? lattice->createDef(driveOp.getValue(), condition)
1295 : lattice->createDef(driveOp->getBlock(),
1297 auto *node = lattice->createNode<DriveNode>(
1298 driveOp, currentSlot, def, valueBefore, lattice->createValue());
1299 valueBefore = node->valueAfter;
1304 if (isa<SignalOp, SigExtractOp, SigArrayGetOp, SigStructExtractOp>(op)) {
1305 if (op->getResult(0) != currentSlot)
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;
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);
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);
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);
1356 if (
auto *probe = dyn_cast<ProbeNode>(node)) {
1357 update(probe->valueBefore,
true);
1367 if (
auto *drive = dyn_cast<DriveNode>(node)) {
1368 bool needed = drive->valueAfter->needed;
1369 if (drive->drivesProjection())
1371 else if (!
isDelayed(drive->slot) && !drive->getDriveOp().getEnable())
1373 update(drive->valueBefore, needed);
1383 if (
auto *slot = dyn_cast<SlotNode>(node)) {
1384 update(slot->valueBefore,
false);
1389 if (
auto *entry = dyn_cast<BlockEntry>(node)) {
1390 for (
auto *predecessor : entry->predecessors)
1391 markDirty(predecessor);
1396 if (
auto *exit = dyn_cast<BlockExit>(node)) {
1399 bool needed =
false;
1400 for (
auto *successor : exit->successors)
1401 needed |= successor->valueAfter->needed;
1402 update(exit->valueBefore, needed);
1406 assert(
false &&
"unhandled node in backward propagation");
1409void Promoter::propagateForward() {
1410 DominanceInfo dominance(region.getParentOp());
1411 propagateForward(
true, dominance);
1412 propagateForward(
false, dominance);
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);
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);
1453 if (
auto *probe = dyn_cast<ProbeNode>(node)) {
1454 update(probe->valueAfter, probe->valueBefore->blockingReachingDef,
1455 probe->valueBefore->delayedReachingDef);
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);
1478 if (drive->drivesProjection() || drive->getDriveOp().getEnable()) {
1479 Def *inDef = driveDelayed ? delayed : blocking;
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();
1491 delayed = drive->def;
1493 blocking = drive->def;
1497 update(drive->valueAfter, blocking, delayed);
1504 if (
auto *slot = dyn_cast<SlotNode>(node)) {
1505 update(slot->valueAfter, slot->def, slot->isSignal() ? slot->def :
nullptr);
1511 if (
auto *entry = dyn_cast<BlockEntry>(node)) {
1514 if (entry->insertedProbe) {
1515 update(entry->valueAfter, entry->insertedProbe, entry->insertedProbe);
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; });
1527 auto mergeFlavor = [&](
bool delayed) -> Def * {
1528 if (!slotDominates || anyPredSuspends)
1532 if (llvm::all_of(entry->predecessors, [&](
auto *p) {
1533 return !p->valueBefore->getReachingDef(delayed);
1539 Def *common =
nullptr;
1540 DriveCondition cond = DriveCondition::never();
1542 for (
auto *pred : entry->predecessors) {
1543 Def *predDef = pred->valueBefore->getReachingDef(delayed);
1544 if (!predDef && optimisticMerges)
1546 DriveCondition predCond =
1547 predDef ? predDef->condition : DriveCondition::never();
1554 if (common != predDef)
1556 if (cond != predCond)
1557 cond = DriveCondition::conditional();
1568 Def *&merged = delayed ? entry->delayedMerged : entry->blockingMerged;
1570 merged->condition = cond;
1581 merged = lattice->createDef(entry->block,
getStoredType(slot), cond);
1585 Def *newBlocking = mergeFlavor(
false);
1586 Def *newDelayed = mergeFlavor(
true);
1587 update(entry->valueAfter, newBlocking, newDelayed);
1592 if (
auto *exit = dyn_cast<BlockExit>(node)) {
1593 for (
auto *successor : exit->successors)
1594 markDirty(successor);
1598 assert(
false &&
"unhandled node in forward propagation");
1602void Promoter::markDirty(LatticeNode *node) {
1607 dirtyNodes.push_back(node);
1618void Promoter::insertProbeBlocks() {
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)
1627 unsigned numIncoming = 0;
1628 for (
auto *predecessor : entry->predecessors)
1629 if (predecessor->valueBefore->needed)
1631 if (numIncoming == 0 || numIncoming == entry->predecessors.size())
1633 for (
auto *predecessor : entry->predecessors)
1634 if (!predecessor->valueBefore->needed)
1635 worklist.insert({predecessor, entry});
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);
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);
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))
1679void Promoter::insertProbes(SlotNode *node) {
1680 auto *op = node->op;
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());
1688 LLVM_DEBUG(llvm::dbgs() <<
"- Inserting probe for " << currentSlot
1689 <<
" after " << *op <<
"\n");
1702void Promoter::hoistSlot(Operation *slotOp) {
1703 auto isInRegion = [&](Value value) {
1704 return region.isAncestor(value.getParentRegion());
1710 SmallVector<Operation *> toMove;
1711 auto *curOp = slotOp;
1715 toMove.push_back(curOp);
1716 for (
auto index : curOp->getOperands().drop_front()) {
1717 if (!isInRegion(index))
1719 auto *indexOp = index.getDefiningOp();
1720 if (!indexOp || !indexOp->hasTrait<OpTrait::ConstantLike>())
1722 toMove.push_back(indexOp);
1724 auto input = curOp->getOperand(0);
1725 if (!isInRegion(input))
1727 curOp = input.getDefiningOp();
1734 for (
auto *op : llvm::reverse(toMove)) {
1735 if (!region.isAncestor(op->getParentRegion()))
1737 LLVM_DEBUG(llvm::dbgs() <<
"- Hoisting " << *op <<
"\n");
1738 op->moveBefore(region.getParentOp());
1744void Promoter::insertProbes(BlockEntry *node) {
1745 if (!node->valueAfter->needed)
1747 if (!node->predecessors.empty() &&
1748 llvm::all_of(node->predecessors, [](
auto *predecessor) {
1749 return predecessor->valueBefore->needed;
1752 LLVM_DEBUG(llvm::dbgs() <<
"- Inserting probe for " << currentSlot
1753 <<
" in block " << node->block <<
"\n");
1754 auto builder = OpBuilder::atBlockBegin(node->block);
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;
1766void Promoter::insertDriveBlocks() {
1770 auto partialAt = [](LatticeValue *before, LatticeValue *after,
bool delayed,
1771 unsigned totalSuccessors) {
1772 Def *def = before->getReachingDef(delayed);
1773 if (!def || def->condition.isNever())
1775 (void)totalSuccessors;
1776 return !after->getReachingDef(delayed);
1779 SmallDenseSet<std::pair<BlockExit *, BlockEntry *>, 1> worklist;
1780 for (
auto *node : lattice->nodes) {
1781 auto *exit = dyn_cast<BlockExit>(node);
1787 for (
bool delayed : {
false,
true}) {
1788 Def *def = exit->valueBefore->getReachingDef(delayed);
1789 if (!def || def->condition.isNever())
1791 unsigned numContinues = 0;
1792 for (
auto *successor : exit->successors)
1793 if (successor->valueAfter->getReachingDef(delayed))
1795 if (numContinues == 0 || numContinues == exit->successors.size())
1797 for (
auto *successor : exit->successors)
1798 if (partialAt(exit->valueBefore, successor->valueAfter, delayed,
1799 exit->successors.size()))
1800 worklist.insert({exit, successor});
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);
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);
1837void Promoter::insertDrives() {
1838 for (
auto *node : lattice->nodes) {
1839 if (
auto *exit = dyn_cast<BlockExit>(node))
1841 else if (
auto *drive = dyn_cast<DriveNode>(node))
1842 insertDrives(drive);
1848void Promoter::insertDrives(BlockExit *node) {
1849 auto builder = OpBuilder::atBlockTerminator(node->block);
1854 auto getDeltaTime = [&]() -> ConstantTimeOp {
1855 auto &cached = delayedTimeCache[node->block];
1857 cached = ConstantTimeOp::create(builder, node->terminator->getLoc(), 0,
1862 auto insertDriveForSlot = [&](
bool delayed) {
1863 Def *reachingDef = node->valueBefore->getReachingDef(delayed);
1864 if (!reachingDef || reachingDef->condition.isNever())
1866 if (!node->suspends && !node->successors.empty() &&
1867 llvm::all_of(node->successors, [&](
auto *successor) {
1868 return successor->valueAfter->getReachingDef(delayed) != nullptr;
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()
1879 DriveOp::create(builder, currentSlot.getLoc(), currentSlot, value,
1880 getDeltaTime(), enable);
1882 AssignOp::create(builder, currentSlot.getLoc(), currentSlot, value,
1886 insertDriveForSlot(
false);
1887 insertDriveForSlot(
true);
1892void Promoter::insertDrives(DriveNode *node) {
1893 LLVM_DEBUG(llvm::dbgs() <<
"- Removing drive " << *node->op <<
"\n");
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);
1913void Promoter::resolveDefinitions(ProbeNode *node) {
1914 Def *def = node->valueBefore->blockingReachingDef;
1915 assert(def &&
"no definition reaches probe");
1918 auto projections =
getProjections(node->op->getOperand(0), node->slot);
1921 auto builder = OpBuilder(node->op);
1922 auto value = def->getValueOrPlaceholder();
1926 LLVM_DEBUG(llvm::dbgs() <<
"- Replacing " << *node->op <<
" with " << value
1928 replaceValueWith(node->op->getResult(0), value);
1935void Promoter::resolveDefinitions(DriveNode *node) {
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);
1948void Promoter::resolveDefinitionValue(DriveNode *node) {
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");
1960 auto builder = OpBuilder(driveOp);
1961 auto value = inDef->getValueOrPlaceholder();
1966 if (!driveOp.getEnable())
1967 value = driveOp.getValue();
1969 value = builder.createOrFold<comb::MuxOp>(
1970 driveOp.getLoc(), driveOp.getEnable(), driveOp.getValue(), value);
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);
1982 node->def->valueIsPlaceholder =
false;
1984 node->def->value = value;
1987void Promoter::resolveDefinitionCondition(DriveNode *node) {
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);
1999 if (inDef->condition.isNever())
2000 condition = driveOp.getEnable();
2003 builder.createOrFold<comb::OrOp>(driveOp.getLoc(), driveOp.getEnable(),
2004 inDef->getConditionOrPlaceholder());
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);
2013 node->def->conditionIsPlaceholder =
false;
2015 node->def->condition.setCondition(condition);
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);
2041bool Promoter::insertBlockArgs(BlockEntry *node) {
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));
2053 if (!node->valueAfter->getReachingDef(
isDelayed(slot)))
2055 if (def->valueIsPlaceholder)
2056 neededSlots.push_back({slot, Which::Value});
2057 if (def->conditionIsPlaceholder)
2058 neededSlots.push_back({slot, Which::Condition});
2062 if (neededSlots.empty())
2064 LLVM_DEBUG(llvm::dbgs() <<
"- Adding " << neededSlots.size()
2065 <<
" args to block " << node->block <<
"\n");
2068 for (
auto [slot, which] : neededSlots) {
2069 auto *def = node->getMerged(
isDelayed(slot));
2072 case Which::Value: {
2075 auto *placeholder = def->value.getDefiningOp();
2076 assert(isa_and_nonnull<UnrealizedConversionCastOp>(placeholder) &&
2077 "placeholder replaced but valueIsPlaceholder still set");
2079 replaceValueWith(placeholder->getResult(0), arg);
2082 def->valueIsPlaceholder =
false;
2085 case Which::Condition: {
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);
2096 def->condition.setCondition(conditionArg);
2097 def->conditionIsPlaceholder =
false;
2104 SmallPtrSet<BlockExit *, 4> updatedPredecessors;
2105 for (
auto *predecessor : node->predecessors) {
2113 if (!updatedPredecessors.insert(predecessor).second)
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);
2124 args.push_back(def->getValueOrPlaceholder());
2130 case Which::Condition:
2132 args.push_back(def->getConditionOrPlaceholder());
2135 builder.getI1Type(), 0));
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);
2153 if (
auto waitOp = dyn_cast<WaitOp>(predecessor->terminator)) {
2154 if (waitOp.getDest() == node->block)
2155 waitOp.getDestOperandsMutable().append(args);
2159 "mem2reg predecessor terminator has no successor operands");
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);
2185void Promoter::removeUnusedLocalSignal(SignalOp signalOp) {
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))
2196 for (
auto *user : op->getUsers())
2197 if (users.insert(user))
2198 worklist.push_back(user);
2203 LLVM_DEBUG(llvm::dbgs() <<
"- Removing local signal " << *signalOp <<
"\n");
2204 for (
auto *op : llvm::reverse(users))
2213struct Mem2RegPass :
public llhd::impl::Mem2RegPassBase<Mem2RegPass> {
2214 void runOnOperation()
override;
2218void Mem2RegPass::runOnOperation() {
2219 SmallVector<Region *> regions;
2220 getOperation()->walk<WalkOrder::PreOrder>([&](Operation *op) {
2221 if (isa<ProcessOp, FinalOp, CombinationalOp, CoroutineOp>(op)) {
2222 auto ®ion = op->getRegion(0);
2223 if (!region.empty())
2224 regions.push_back(®ion);
2225 return WalkResult::skip();
2227 return WalkResult::advance();
2229 for (
auto *region : regions)
2230 if (failed(Promoter(*region).promote()))
2231 return signalPassFailure();
static bool isAlways(Attribute attr, bool expected)
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)
static bool isDelayed(DefSlot slot)
static bool isPromotableSlotType(Type type)
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...
static Location getLoc(DefSlot slot)
static ProjectionStack getProjections(Value fromSignal, Value toSlot)
Collect the llhd.sig.
static bool isDeltaDrive(const Operation *op)
Check whether an operation is a llhd.drv with a delta delay.
static DefSlot blockingSlot(Value slot)
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 ...
static bool isBlockingDrive(const Operation *op)
Check whether an operation is an llhd.assign.
static DefSlot delayedSlot(Value slot)
static Value getSlot(DefSlot slot)
static Type getStoredType(DefSlot slot)
SmallVector< Projection > ProjectionStack
A stack of projection operations.
PointerIntPair< Value, 1 > DefSlot
The slot a reaching definition specifies a value for, alongside a bit indicating whether the definiti...
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.
Value createDynamicExtract(OpBuilder &builder, Location loc, Value value, Value offset, unsigned width)
Extract a range of bits from an integer at a dynamic offset.
static bool operator==(const ModulePort &a, const ModulePort &b)
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
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)
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)
static unsigned getHashValue(DriveCondition d)