1//===- IRNumbering.cpp - MLIR Bytecode IR numbering -----------------------===//
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 "IRNumbering.h"
10#include "mlir/Bytecode/BytecodeImplementation.h"
11#include "mlir/Bytecode/BytecodeOpInterface.h"
12#include "mlir/Bytecode/BytecodeWriter.h"
13#include "mlir/Bytecode/Encoding.h"
14#include "mlir/IR/AsmState.h"
15#include "mlir/IR/BuiltinTypes.h"
16#include "mlir/IR/Location.h"
17#include "mlir/IR/OpDefinition.h"
18
19using namespace mlir;
20using namespace mlir::bytecode::detail;
21
22//===----------------------------------------------------------------------===//
23// NumberingDialectWriter
24//===----------------------------------------------------------------------===//
25
26struct IRNumberingState::NumberingDialectWriter : public DialectBytecodeWriter {
27 NumberingDialectWriter(
28 IRNumberingState &state,
29 llvm::StringMap<std::unique_ptr<DialectVersion>> &dialectVersionMap)
30 : state(state), dialectVersionMap(dialectVersionMap) {}
31
32 void writeAttribute(Attribute attr) override { state.number(attr); }
33 void writeOptionalAttribute(Attribute attr) override {
34 if (attr)
35 state.number(attr);
36 }
37 void writeType(Type type) override { state.number(type); }
38 void writeResourceHandle(const AsmDialectResourceHandle &resource) override {
39 state.number(dialect: resource.getDialect(), resources: resource);
40 }
41
42 /// Stubbed out methods that are not used for numbering.
43 void writeVarInt(uint64_t) override {}
44 void writeSignedVarInt(int64_t value) override {}
45 void writeAPIntWithKnownWidth(const APInt &value) override {}
46 void writeAPFloatWithKnownSemantics(const APFloat &value) override {}
47 void writeOwnedString(StringRef) override {
48 // TODO: It might be nice to prenumber strings and sort by the number of
49 // references. This could potentially be useful for optimizing things like
50 // file locations.
51 }
52 void writeOwnedBlob(ArrayRef<char> blob) override {}
53 void writeOwnedBool(bool value) override {}
54 void writeUnownedBlob(ArrayRef<char> blob) override {}
55
56 int64_t getBytecodeVersion() const override {
57 return state.getDesiredBytecodeVersion();
58 }
59
60 FailureOr<const DialectVersion *>
61 getDialectVersion(StringRef dialectName) const override {
62 auto dialectEntry = dialectVersionMap.find(Key: dialectName);
63 if (dialectEntry == dialectVersionMap.end())
64 return failure();
65 return dialectEntry->getValue().get();
66 }
67
68 /// The parent numbering state that is populated by this writer.
69 IRNumberingState &state;
70
71 /// A map containing dialect version information for each dialect to emit.
72 llvm::StringMap<std::unique_ptr<DialectVersion>> &dialectVersionMap;
73};
74
75//===----------------------------------------------------------------------===//
76// IR Numbering
77//===----------------------------------------------------------------------===//
78
79/// Group and sort the elements of the given range by their parent dialect. This
80/// grouping is applied to sub-sections of the ranged defined by how many bytes
81/// it takes to encode a varint index to that sub-section.
82template <typename T>
83static void groupByDialectPerByte(T range) {
84 if (range.empty())
85 return;
86
87 // A functor used to sort by a given dialect, with a desired dialect to be
88 // ordered first (to better enable sharing of dialects across byte groups).
89 auto sortByDialect = [](unsigned dialectToOrderFirst, const auto &lhs,
90 const auto &rhs) {
91 if (lhs->dialect->number == dialectToOrderFirst)
92 return rhs->dialect->number != dialectToOrderFirst;
93 if (rhs->dialect->number == dialectToOrderFirst)
94 return false;
95 return lhs->dialect->number < rhs->dialect->number;
96 };
97
98 unsigned dialectToOrderFirst = 0;
99 size_t elementsInByteGroup = 0;
100 auto iterRange = range;
101 for (unsigned i = 1; i < 9; ++i) {
102 // Update the number of elements in the current byte grouping. Reminder
103 // that varint encodes 7-bits per byte, so that's how we compute the
104 // number of elements in each byte grouping.
105 elementsInByteGroup = (1ULL << (7ULL * i)) - elementsInByteGroup;
106
107 // Slice out the sub-set of elements that are in the current byte grouping
108 // to be sorted.
109 auto byteSubRange = iterRange.take_front(elementsInByteGroup);
110 iterRange = iterRange.drop_front(byteSubRange.size());
111
112 // Sort the sub range for this byte.
113 llvm::stable_sort(byteSubRange, [&](const auto &lhs, const auto &rhs) {
114 return sortByDialect(dialectToOrderFirst, lhs, rhs);
115 });
116
117 // Update the dialect to order first to be the dialect at the end of the
118 // current grouping. This seeks to allow larger dialect groupings across
119 // byte boundaries.
120 dialectToOrderFirst = byteSubRange.back()->dialect->number;
121
122 // If the data range is now empty, we are done.
123 if (iterRange.empty())
124 break;
125 }
126
127 // Assign the entry numbers based on the sort order.
128 for (auto [idx, value] : llvm::enumerate(range))
129 value->number = idx;
130}
131
132IRNumberingState::IRNumberingState(Operation *op,
133 const BytecodeWriterConfig &config)
134 : config(config) {
135 computeGlobalNumberingState(rootOp: op);
136
137 // Number the root operation.
138 number(op&: *op);
139
140 // A worklist of region contexts to number and the next value id before that
141 // region.
142 SmallVector<std::pair<Region *, unsigned>, 8> numberContext;
143
144 // Functor to push the regions of the given operation onto the numbering
145 // context.
146 auto addOpRegionsToNumber = [&](Operation *op) {
147 MutableArrayRef<Region> regions = op->getRegions();
148 if (regions.empty())
149 return;
150
151 // Isolated regions don't share value numbers with their parent, so we can
152 // start numbering these regions at zero.
153 unsigned opFirstValueID = isIsolatedFromAbove(op) ? 0 : nextValueID;
154 for (Region &region : regions)
155 numberContext.emplace_back(Args: &region, Args&: opFirstValueID);
156 };
157 addOpRegionsToNumber(op);
158
159 // Iteratively process each of the nested regions.
160 while (!numberContext.empty()) {
161 Region *region;
162 std::tie(args&: region, args&: nextValueID) = numberContext.pop_back_val();
163 number(region&: *region);
164
165 // Traverse into nested regions.
166 for (Operation &op : region->getOps())
167 addOpRegionsToNumber(&op);
168 }
169
170 // Number each of the dialects. For now this is just in the order they were
171 // found, given that the number of dialects on average is small enough to fit
172 // within a singly byte (128). If we ever have real world use cases that have
173 // a huge number of dialects, this could be made more intelligent.
174 for (auto [idx, dialect] : llvm::enumerate(First&: dialects))
175 dialect.second->number = idx;
176
177 // Number each of the recorded components within each dialect.
178
179 // First sort by ref count so that the most referenced elements are first. We
180 // try to bias more heavily used elements to the front. This allows for more
181 // frequently referenced things to be encoded using smaller varints.
182 auto sortByRefCountFn = [](const auto &lhs, const auto &rhs) {
183 return lhs->refCount > rhs->refCount;
184 };
185 llvm::stable_sort(Range&: orderedAttrs, C: sortByRefCountFn);
186 llvm::stable_sort(Range&: orderedOpNames, C: sortByRefCountFn);
187 llvm::stable_sort(Range&: orderedTypes, C: sortByRefCountFn);
188
189 // After that, we apply a secondary ordering based on the parent dialect. This
190 // ordering is applied to sub-sections of the element list defined by how many
191 // bytes it takes to encode a varint index to that sub-section. This allows
192 // for more efficiently encoding components of the same dialect (e.g. we only
193 // have to encode the dialect reference once).
194 groupByDialectPerByte(range: llvm::MutableArrayRef(orderedAttrs));
195 groupByDialectPerByte(range: llvm::MutableArrayRef(orderedOpNames));
196 groupByDialectPerByte(range: llvm::MutableArrayRef(orderedTypes));
197
198 // Finalize the numbering of the dialect resources.
199 finalizeDialectResourceNumberings(rootOp: op);
200}
201
202unsigned IRNumberingState::getNumber(Location loc) {
203 if (config.shouldElideLocations()) {
204 return getNumber(attr: Attribute(UnknownLoc::get(context: loc.getContext())));
205 }
206 return getNumber(attr: Attribute(loc));
207}
208
209void IRNumberingState::computeGlobalNumberingState(Operation *rootOp) {
210 // A simple state struct tracking data used when walking operations.
211 struct StackState {
212 /// The operation currently being walked.
213 Operation *op;
214
215 /// The numbering of the operation.
216 OperationNumbering *numbering;
217
218 /// A flag indicating if the current state or one of its parents has
219 /// unresolved isolation status. This is tracked separately from the
220 /// isIsolatedFromAbove bit on `numbering` because we need to be able to
221 /// handle the given case:
222 /// top.op {
223 /// %value = ...
224 /// middle.op {
225 /// %value2 = ...
226 /// inner.op {
227 /// // Here we mark `inner.op` as not isolated. Note `middle.op`
228 /// // isn't known not isolated yet.
229 /// use.op %value2
230 ///
231 /// // Here inner.op is already known to be non-isolated, but
232 /// // `middle.op` is now also discovered to be non-isolated.
233 /// use.op %value
234 /// }
235 /// }
236 /// }
237 bool hasUnresolvedIsolation;
238 };
239
240 // Compute a global operation ID numbering according to the pre-order walk of
241 // the IR. This is used as reference to construct use-list orders.
242 unsigned operationID = 0;
243
244 // Walk each of the operations within the IR, tracking a stack of operations
245 // as we recurse into nested regions. This walk method hooks in at two stages
246 // during the walk:
247 //
248 // BeforeAllRegions:
249 // Here we generate a numbering for the operation and push it onto the
250 // stack if it has regions. We also compute the isolation status of parent
251 // regions at this stage. This is done by checking the parent regions of
252 // operands used by the operation, and marking each region between the
253 // the operand region and the current as not isolated. See
254 // StackState::hasUnresolvedIsolation above for an example.
255 //
256 // AfterAllRegions:
257 // Here we pop the operation from the stack, and if it hasn't been marked
258 // as non-isolated, we mark it as so. A non-isolated use would have been
259 // found while walking the regions, so it is safe to mark the operation at
260 // this point.
261 //
262 SmallVector<StackState> opStack;
263 rootOp->walk(callback: [&](Operation *op, const WalkStage &stage) {
264 // After visiting all nested regions, we pop the operation from the stack.
265 if (op->getNumRegions() && stage.isAfterAllRegions()) {
266 // If no non-isolated uses were found, we can safely mark this operation
267 // as isolated from above.
268 OperationNumbering *numbering = opStack.pop_back_val().numbering;
269 if (!numbering->isIsolatedFromAbove.has_value())
270 numbering->isIsolatedFromAbove = true;
271 return;
272 }
273
274 // When visiting before nested regions, we process "IsolatedFromAbove"
275 // checks and compute the number for this operation.
276 if (!stage.isBeforeAllRegions())
277 return;
278 // Update the isolation status of parent regions if any have yet to be
279 // resolved.
280 if (!opStack.empty() && opStack.back().hasUnresolvedIsolation) {
281 Region *parentRegion = op->getParentRegion();
282 for (Value operand : op->getOperands()) {
283 Region *operandRegion = operand.getParentRegion();
284 if (operandRegion == parentRegion)
285 continue;
286 // We've found a use of an operand outside of the current region,
287 // walk the operation stack searching for the parent operation,
288 // marking every region on the way as not isolated.
289 Operation *operandContainerOp = operandRegion->getParentOp();
290 auto it = std::find_if(
291 first: opStack.rbegin(), last: opStack.rend(), pred: [=](const StackState &it) {
292 // We only need to mark up to the container region, or the first
293 // that has an unresolved status.
294 return !it.hasUnresolvedIsolation || it.op == operandContainerOp;
295 });
296 assert(it != opStack.rend() && "expected to find the container");
297 for (auto &state : llvm::make_range(x: opStack.rbegin(), y: it)) {
298 // If we stopped at a region that knows its isolation status, we can
299 // stop updating the isolation status for the parent regions.
300 state.hasUnresolvedIsolation = it->hasUnresolvedIsolation;
301 state.numbering->isIsolatedFromAbove = false;
302 }
303 }
304 }
305
306 // Compute the number for this op and push it onto the stack.
307 auto *numbering =
308 new (opAllocator.Allocate()) OperationNumbering(operationID++);
309 if (op->hasTrait<OpTrait::IsIsolatedFromAbove>())
310 numbering->isIsolatedFromAbove = true;
311 operations.try_emplace(Key: op, Args&: numbering);
312 if (op->getNumRegions()) {
313 opStack.emplace_back(Args: StackState{
314 .op: op, .numbering: numbering, .hasUnresolvedIsolation: !numbering->isIsolatedFromAbove.has_value()});
315 }
316 });
317}
318
319void IRNumberingState::number(Location loc) {
320 if (config.shouldElideLocations()) {
321 number(attr: Attribute(UnknownLoc::get(context: loc.getContext())));
322 } else {
323 number(attr: Attribute(loc));
324 }
325}
326
327void IRNumberingState::number(Attribute attr) {
328 auto it = attrs.try_emplace(Key: attr);
329 if (!it.second) {
330 ++it.first->second->refCount;
331 return;
332 }
333 auto *numbering = new (attrAllocator.Allocate()) AttributeNumbering(attr);
334 it.first->second = numbering;
335 orderedAttrs.push_back(x: numbering);
336
337 // Check for OpaqueAttr, which is a dialect-specific attribute that didn't
338 // have a registered dialect when it got created. We don't want to encode this
339 // as the builtin OpaqueAttr, we want to encode it as if the dialect was
340 // actually loaded.
341 if (OpaqueAttr opaqueAttr = dyn_cast<OpaqueAttr>(Val&: attr)) {
342 numbering->dialect = &numberDialect(dialect: opaqueAttr.getDialectNamespace());
343 return;
344 }
345 numbering->dialect = &numberDialect(dialect: &attr.getDialect());
346
347 // If this attribute will be emitted using the bytecode format, perform a
348 // dummy writing to number any nested components.
349 // TODO: We don't allow custom encodings for mutable attributes right now.
350 if (!attr.hasTrait<AttributeTrait::IsMutable>()) {
351 // Try overriding emission with callbacks.
352 for (const auto &callback : config.getAttributeWriterCallbacks()) {
353 NumberingDialectWriter writer(*this, config.getDialectVersionMap());
354 // The client has the ability to override the group name through the
355 // callback.
356 std::optional<StringRef> groupNameOverride;
357 if (succeeded(Result: callback->write(entry: attr, name&: groupNameOverride, writer))) {
358 if (groupNameOverride.has_value())
359 numbering->dialect = &numberDialect(dialect: *groupNameOverride);
360 return;
361 }
362 }
363
364 if (const auto *interface = numbering->dialect->interface) {
365 NumberingDialectWriter writer(*this, config.getDialectVersionMap());
366 if (succeeded(Result: interface->writeAttribute(attribute: attr, writer)))
367 return;
368 }
369 }
370 // If this attribute will be emitted using the fallback, number the nested
371 // dialect resources. We don't number everything (e.g. no nested
372 // attributes/types), because we don't want to encode things we won't decode
373 // (the textual format can't really share much).
374 AsmState tempState(attr.getContext());
375 llvm::raw_null_ostream dummyOS;
376 attr.print(os&: dummyOS, state&: tempState);
377
378 // Number the used dialect resources.
379 for (const auto &it : tempState.getDialectResources())
380 number(dialect: it.getFirst(), resources: it.getSecond().getArrayRef());
381}
382
383void IRNumberingState::number(Block &block) {
384 // Number the arguments of the block.
385 for (BlockArgument arg : block.getArguments()) {
386 valueIDs.try_emplace(Key: arg, Args: nextValueID++);
387 number(loc: arg.getLoc());
388 number(type: arg.getType());
389 }
390
391 // Number the operations in this block.
392 unsigned &numOps = blockOperationCounts[&block];
393 for (Operation &op : block) {
394 number(op);
395 ++numOps;
396 }
397}
398
399auto IRNumberingState::numberDialect(Dialect *dialect) -> DialectNumbering & {
400 DialectNumbering *&numbering = registeredDialects[dialect];
401 if (!numbering) {
402 numbering = &numberDialect(dialect: dialect->getNamespace());
403 numbering->interface = dyn_cast<BytecodeDialectInterface>(Val: dialect);
404 numbering->asmInterface = dyn_cast<OpAsmDialectInterface>(Val: dialect);
405 }
406 return *numbering;
407}
408
409auto IRNumberingState::numberDialect(StringRef dialect) -> DialectNumbering & {
410 DialectNumbering *&numbering = dialects[dialect];
411 if (!numbering) {
412 numbering = new (dialectAllocator.Allocate())
413 DialectNumbering(dialect, dialects.size() - 1);
414 }
415 return *numbering;
416}
417
418void IRNumberingState::number(Region &region) {
419 if (region.empty())
420 return;
421 size_t firstValueID = nextValueID;
422
423 // Number the blocks within this region.
424 size_t blockCount = 0;
425 for (auto it : llvm::enumerate(First&: region)) {
426 blockIDs.try_emplace(Key: &it.value(), Args: it.index());
427 number(block&: it.value());
428 ++blockCount;
429 }
430
431 // Remember the number of blocks and values in this region.
432 regionBlockValueCounts.try_emplace(Key: &region, Args&: blockCount,
433 Args: nextValueID - firstValueID);
434}
435
436void IRNumberingState::number(Operation &op) {
437 // Number the components of an operation that won't be numbered elsewhere
438 // (e.g. we don't number operands, regions, or successors here).
439 number(opName: op.getName());
440 for (OpResult result : op.getResults()) {
441 valueIDs.try_emplace(Key: result, Args: nextValueID++);
442 number(type: result.getType());
443 }
444
445 // Prior to a version with native property encoding, or when properties are
446 // not used, we need to number also the merged dictionary containing both the
447 // inherent and discardable attribute.
448 DictionaryAttr dictAttr;
449 if (config.getDesiredBytecodeVersion() >=
450 bytecode::kNativePropertiesEncoding ||
451 !op.getPropertiesStorage())
452 dictAttr = op.getRawDictionaryAttrs();
453 else {
454 NamedAttrList attrs;
455 op.getName().walkInherentAttrs(op: &op, visitor: [&](StringRef name, Attribute &attr) {
456 attrs.append(name, attr);
457 });
458 attrs.append(newAttributes: op.getDiscardableAttrDictionary().getValue());
459 dictAttr = attrs.getDictionary(context: op.getContext());
460 }
461 // Only number the operation's dictionary if it isn't empty.
462 if (!dictAttr.empty())
463 number(attr: dictAttr);
464
465 // Visit the operation properties (if any) to make sure referenced attributes
466 // are numbered.
467 if (config.getDesiredBytecodeVersion() >=
468 bytecode::kNativePropertiesEncoding &&
469 op.getPropertiesStorageSize()) {
470 if (op.isRegistered()) {
471 // Operation that have properties *must* implement this interface.
472 auto iface = cast<BytecodeOpInterface>(Val&: op);
473 NumberingDialectWriter writer(*this, config.getDialectVersionMap());
474 iface.writeProperties(writer);
475 } else {
476 // Unregistered op are storing properties as an optional attribute.
477 if (Attribute prop = *op.getPropertiesStorage().as<Attribute *>())
478 number(attr: prop);
479 }
480 }
481
482 number(loc: op.getLoc());
483}
484
485void IRNumberingState::number(OperationName opName) {
486 OpNameNumbering *&numbering = opNames[opName];
487 if (numbering) {
488 ++numbering->refCount;
489 return;
490 }
491 DialectNumbering *dialectNumber = nullptr;
492 if (Dialect *dialect = opName.getDialect())
493 dialectNumber = &numberDialect(dialect);
494 else
495 dialectNumber = &numberDialect(dialect: opName.getDialectNamespace());
496
497 numbering =
498 new (opNameAllocator.Allocate()) OpNameNumbering(dialectNumber, opName);
499 orderedOpNames.push_back(x: numbering);
500}
501
502void IRNumberingState::number(Type type) {
503 auto it = types.try_emplace(Key: type);
504 if (!it.second) {
505 ++it.first->second->refCount;
506 return;
507 }
508 auto *numbering = new (typeAllocator.Allocate()) TypeNumbering(type);
509 it.first->second = numbering;
510 orderedTypes.push_back(x: numbering);
511
512 // Check for OpaqueType, which is a dialect-specific type that didn't have a
513 // registered dialect when it got created. We don't want to encode this as the
514 // builtin OpaqueType, we want to encode it as if the dialect was actually
515 // loaded.
516 if (OpaqueType opaqueType = dyn_cast<OpaqueType>(Val&: type)) {
517 numbering->dialect = &numberDialect(dialect: opaqueType.getDialectNamespace());
518 return;
519 }
520 numbering->dialect = &numberDialect(dialect: &type.getDialect());
521
522 // If this type will be emitted using the bytecode format, perform a dummy
523 // writing to number any nested components. Mutable types are allowed: the
524 // numbering above inserts `type` into the map *before* this point, so a
525 // nested reference back to it hits the early return at the top of this
526 // function, and the reader side breaks the same cycle with
527 // DialectBytecodeReader::tryStartCyclicRead.
528 // Try overriding emission with callbacks.
529 for (const auto &callback : config.getTypeWriterCallbacks()) {
530 NumberingDialectWriter writer(*this, config.getDialectVersionMap());
531 // The client has the ability to override the group name through the
532 // callback.
533 std::optional<StringRef> groupNameOverride;
534 if (succeeded(Result: callback->write(entry: type, name&: groupNameOverride, writer))) {
535 if (groupNameOverride.has_value())
536 numbering->dialect = &numberDialect(dialect: *groupNameOverride);
537 return;
538 }
539 }
540
541 // If this attribute will be emitted using the bytecode format, perform a
542 // dummy writing to number any nested components.
543 if (const auto *interface = numbering->dialect->interface) {
544 NumberingDialectWriter writer(*this, config.getDialectVersionMap());
545 if (succeeded(Result: interface->writeType(type, writer)))
546 return;
547 }
548 // If this type will be emitted using the fallback, number the nested dialect
549 // resources. We don't number everything (e.g. no nested attributes/types),
550 // because we don't want to encode things we won't decode (the textual format
551 // can't really share much).
552 AsmState tempState(type.getContext());
553 llvm::raw_null_ostream dummyOS;
554 type.print(os&: dummyOS, state&: tempState);
555
556 // Number the used dialect resources.
557 for (const auto &it : tempState.getDialectResources())
558 number(dialect: it.getFirst(), resources: it.getSecond().getArrayRef());
559}
560
561void IRNumberingState::number(Dialect *dialect,
562 ArrayRef<AsmDialectResourceHandle> resources) {
563 DialectNumbering &dialectNumber = numberDialect(dialect);
564 assert(
565 dialectNumber.asmInterface &&
566 "expected dialect owning a resource to implement OpAsmDialectInterface");
567
568 for (const auto &resource : resources) {
569 // Check if this is a newly seen resource.
570 if (!dialectNumber.resources.insert(X: resource))
571 return;
572
573 auto *numbering =
574 new (resourceAllocator.Allocate()) DialectResourceNumbering(
575 dialectNumber.asmInterface->getResourceKey(handle: resource));
576 dialectNumber.resourceMap.insert(KV: {numbering->key, numbering});
577 dialectResources.try_emplace(Key: resource, Args&: numbering);
578 }
579}
580
581int64_t IRNumberingState::getDesiredBytecodeVersion() const {
582 return config.getDesiredBytecodeVersion();
583}
584
585namespace {
586/// A dummy resource builder used to number dialect resources.
587struct NumberingResourceBuilder : public AsmResourceBuilder {
588 NumberingResourceBuilder(DialectNumbering *dialect, unsigned &nextResourceID)
589 : dialect(dialect), nextResourceID(nextResourceID) {}
590 ~NumberingResourceBuilder() override = default;
591
592 void buildBlob(StringRef key, ArrayRef<char>, uint32_t) final {
593 numberEntry(key);
594 }
595 void buildBool(StringRef key, bool) final { numberEntry(key); }
596 void buildString(StringRef key, StringRef) final {
597 // TODO: We could pre-number the value string here as well.
598 numberEntry(key);
599 }
600
601 /// Number the dialect entry for the given key.
602 void numberEntry(StringRef key) {
603 // TODO: We could pre-number resource key strings here as well.
604
605 auto *it = dialect->resourceMap.find(Key: key);
606 if (it != dialect->resourceMap.end()) {
607 it->second->number = nextResourceID++;
608 it->second->isDeclaration = false;
609 }
610 }
611
612 DialectNumbering *dialect;
613 unsigned &nextResourceID;
614};
615} // namespace
616
617void IRNumberingState::finalizeDialectResourceNumberings(Operation *rootOp) {
618 unsigned nextResourceID = 0;
619 for (DialectNumbering &dialect : getDialects()) {
620 if (!dialect.asmInterface)
621 continue;
622 NumberingResourceBuilder entryBuilder(&dialect, nextResourceID);
623 dialect.asmInterface->buildResources(op: rootOp, referencedResources: dialect.resources,
624 builder&: entryBuilder);
625
626 // Number any resources that weren't added by the dialect. This can happen
627 // if there was no backing data to the resource, but we still want these
628 // resource references to roundtrip, so we number them and indicate that the
629 // data is missing.
630 for (const auto &it : dialect.resourceMap)
631 if (it.second->isDeclaration)
632 it.second->number = nextResourceID++;
633 }
634}
635