xref: /llvm-project-15.0.7/mlir/lib/CAPI/IR/IR.cpp (revision faef447e)
1 //===- IR.cpp - C Interface for Core MLIR APIs ----------------------------===//
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 "mlir-c/IR.h"
10 #include "mlir-c/Support.h"
11 
12 #include "mlir/CAPI/IR.h"
13 #include "mlir/CAPI/Support.h"
14 #include "mlir/CAPI/Utils.h"
15 #include "mlir/IR/Attributes.h"
16 #include "mlir/IR/BuiltinOps.h"
17 #include "mlir/IR/Dialect.h"
18 #include "mlir/IR/Location.h"
19 #include "mlir/IR/Operation.h"
20 #include "mlir/IR/Types.h"
21 #include "mlir/IR/Verifier.h"
22 #include "mlir/Interfaces/InferTypeOpInterface.h"
23 #include "mlir/Parser/Parser.h"
24 
25 #include "llvm/Support/Debug.h"
26 #include <cstddef>
27 
28 using namespace mlir;
29 
30 //===----------------------------------------------------------------------===//
31 // Context API.
32 //===----------------------------------------------------------------------===//
33 
34 MlirContext mlirContextCreate() {
35   auto *context = new MLIRContext;
36   return wrap(context);
37 }
38 
39 bool mlirContextEqual(MlirContext ctx1, MlirContext ctx2) {
40   return unwrap(ctx1) == unwrap(ctx2);
41 }
42 
43 void mlirContextDestroy(MlirContext context) { delete unwrap(context); }
44 
45 void mlirContextSetAllowUnregisteredDialects(MlirContext context, bool allow) {
46   unwrap(context)->allowUnregisteredDialects(allow);
47 }
48 
49 bool mlirContextGetAllowUnregisteredDialects(MlirContext context) {
50   return unwrap(context)->allowsUnregisteredDialects();
51 }
52 intptr_t mlirContextGetNumRegisteredDialects(MlirContext context) {
53   return static_cast<intptr_t>(unwrap(context)->getAvailableDialects().size());
54 }
55 
56 void mlirContextAppendDialectRegistry(MlirContext ctx,
57                                       MlirDialectRegistry registry) {
58   unwrap(ctx)->appendDialectRegistry(*unwrap(registry));
59 }
60 
61 // TODO: expose a cheaper way than constructing + sorting a vector only to take
62 // its size.
63 intptr_t mlirContextGetNumLoadedDialects(MlirContext context) {
64   return static_cast<intptr_t>(unwrap(context)->getLoadedDialects().size());
65 }
66 
67 MlirDialect mlirContextGetOrLoadDialect(MlirContext context,
68                                         MlirStringRef name) {
69   return wrap(unwrap(context)->getOrLoadDialect(unwrap(name)));
70 }
71 
72 bool mlirContextIsRegisteredOperation(MlirContext context, MlirStringRef name) {
73   return unwrap(context)->isOperationRegistered(unwrap(name));
74 }
75 
76 void mlirContextEnableMultithreading(MlirContext context, bool enable) {
77   return unwrap(context)->enableMultithreading(enable);
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // Dialect API.
82 //===----------------------------------------------------------------------===//
83 
84 MlirContext mlirDialectGetContext(MlirDialect dialect) {
85   return wrap(unwrap(dialect)->getContext());
86 }
87 
88 bool mlirDialectEqual(MlirDialect dialect1, MlirDialect dialect2) {
89   return unwrap(dialect1) == unwrap(dialect2);
90 }
91 
92 MlirStringRef mlirDialectGetNamespace(MlirDialect dialect) {
93   return wrap(unwrap(dialect)->getNamespace());
94 }
95 
96 //===----------------------------------------------------------------------===//
97 // DialectRegistry API.
98 //===----------------------------------------------------------------------===//
99 
100 MlirDialectRegistry mlirDialectRegistryCreate() {
101   return wrap(new DialectRegistry());
102 }
103 
104 void mlirDialectRegistryDestroy(MlirDialectRegistry registry) {
105   delete unwrap(registry);
106 }
107 
108 //===----------------------------------------------------------------------===//
109 // Printing flags API.
110 //===----------------------------------------------------------------------===//
111 
112 MlirOpPrintingFlags mlirOpPrintingFlagsCreate() {
113   return wrap(new OpPrintingFlags());
114 }
115 
116 void mlirOpPrintingFlagsDestroy(MlirOpPrintingFlags flags) {
117   delete unwrap(flags);
118 }
119 
120 void mlirOpPrintingFlagsElideLargeElementsAttrs(MlirOpPrintingFlags flags,
121                                                 intptr_t largeElementLimit) {
122   unwrap(flags)->elideLargeElementsAttrs(largeElementLimit);
123 }
124 
125 void mlirOpPrintingFlagsEnableDebugInfo(MlirOpPrintingFlags flags,
126                                         bool prettyForm) {
127   unwrap(flags)->enableDebugInfo(/*prettyForm=*/prettyForm);
128 }
129 
130 void mlirOpPrintingFlagsPrintGenericOpForm(MlirOpPrintingFlags flags) {
131   unwrap(flags)->printGenericOpForm();
132 }
133 
134 void mlirOpPrintingFlagsUseLocalScope(MlirOpPrintingFlags flags) {
135   unwrap(flags)->useLocalScope();
136 }
137 
138 //===----------------------------------------------------------------------===//
139 // Location API.
140 //===----------------------------------------------------------------------===//
141 
142 MlirLocation mlirLocationFileLineColGet(MlirContext context,
143                                         MlirStringRef filename, unsigned line,
144                                         unsigned col) {
145   return wrap(Location(
146       FileLineColLoc::get(unwrap(context), unwrap(filename), line, col)));
147 }
148 
149 MlirLocation mlirLocationCallSiteGet(MlirLocation callee, MlirLocation caller) {
150   return wrap(Location(CallSiteLoc::get(unwrap(callee), unwrap(caller))));
151 }
152 
153 MlirLocation mlirLocationFusedGet(MlirContext ctx, intptr_t nLocations,
154                                   MlirLocation const *locations,
155                                   MlirAttribute metadata) {
156   SmallVector<Location, 4> locs;
157   ArrayRef<Location> unwrappedLocs = unwrapList(nLocations, locations, locs);
158   return wrap(FusedLoc::get(unwrappedLocs, unwrap(metadata), unwrap(ctx)));
159 }
160 
161 MlirLocation mlirLocationNameGet(MlirContext context, MlirStringRef name,
162                                  MlirLocation childLoc) {
163   if (mlirLocationIsNull(childLoc))
164     return wrap(
165         Location(NameLoc::get(StringAttr::get(unwrap(context), unwrap(name)))));
166   return wrap(Location(NameLoc::get(
167       StringAttr::get(unwrap(context), unwrap(name)), unwrap(childLoc))));
168 }
169 
170 MlirLocation mlirLocationUnknownGet(MlirContext context) {
171   return wrap(Location(UnknownLoc::get(unwrap(context))));
172 }
173 
174 bool mlirLocationEqual(MlirLocation l1, MlirLocation l2) {
175   return unwrap(l1) == unwrap(l2);
176 }
177 
178 MlirContext mlirLocationGetContext(MlirLocation location) {
179   return wrap(unwrap(location).getContext());
180 }
181 
182 void mlirLocationPrint(MlirLocation location, MlirStringCallback callback,
183                        void *userData) {
184   detail::CallbackOstream stream(callback, userData);
185   unwrap(location).print(stream);
186 }
187 
188 //===----------------------------------------------------------------------===//
189 // Module API.
190 //===----------------------------------------------------------------------===//
191 
192 MlirModule mlirModuleCreateEmpty(MlirLocation location) {
193   return wrap(ModuleOp::create(unwrap(location)));
194 }
195 
196 MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module) {
197   OwningOpRef<ModuleOp> owning =
198       parseSourceString<ModuleOp>(unwrap(module), unwrap(context));
199   if (!owning)
200     return MlirModule{nullptr};
201   return MlirModule{owning.release().getOperation()};
202 }
203 
204 MlirContext mlirModuleGetContext(MlirModule module) {
205   return wrap(unwrap(module).getContext());
206 }
207 
208 MlirBlock mlirModuleGetBody(MlirModule module) {
209   return wrap(unwrap(module).getBody());
210 }
211 
212 void mlirModuleDestroy(MlirModule module) {
213   // Transfer ownership to an OwningOpRef<ModuleOp> so that its destructor is
214   // called.
215   OwningOpRef<ModuleOp>(unwrap(module));
216 }
217 
218 MlirOperation mlirModuleGetOperation(MlirModule module) {
219   return wrap(unwrap(module).getOperation());
220 }
221 
222 MlirModule mlirModuleFromOperation(MlirOperation op) {
223   return wrap(dyn_cast<ModuleOp>(unwrap(op)));
224 }
225 
226 //===----------------------------------------------------------------------===//
227 // Operation state API.
228 //===----------------------------------------------------------------------===//
229 
230 MlirOperationState mlirOperationStateGet(MlirStringRef name, MlirLocation loc) {
231   MlirOperationState state;
232   state.name = name;
233   state.location = loc;
234   state.nResults = 0;
235   state.results = nullptr;
236   state.nOperands = 0;
237   state.operands = nullptr;
238   state.nRegions = 0;
239   state.regions = nullptr;
240   state.nSuccessors = 0;
241   state.successors = nullptr;
242   state.nAttributes = 0;
243   state.attributes = nullptr;
244   state.enableResultTypeInference = false;
245   return state;
246 }
247 
248 #define APPEND_ELEMS(type, sizeName, elemName)                                 \
249   state->elemName =                                                            \
250       (type *)realloc(state->elemName, (state->sizeName + n) * sizeof(type));  \
251   memcpy(state->elemName + state->sizeName, elemName, n * sizeof(type));       \
252   state->sizeName += n;
253 
254 void mlirOperationStateAddResults(MlirOperationState *state, intptr_t n,
255                                   MlirType const *results) {
256   APPEND_ELEMS(MlirType, nResults, results);
257 }
258 
259 void mlirOperationStateAddOperands(MlirOperationState *state, intptr_t n,
260                                    MlirValue const *operands) {
261   APPEND_ELEMS(MlirValue, nOperands, operands);
262 }
263 void mlirOperationStateAddOwnedRegions(MlirOperationState *state, intptr_t n,
264                                        MlirRegion const *regions) {
265   APPEND_ELEMS(MlirRegion, nRegions, regions);
266 }
267 void mlirOperationStateAddSuccessors(MlirOperationState *state, intptr_t n,
268                                      MlirBlock const *successors) {
269   APPEND_ELEMS(MlirBlock, nSuccessors, successors);
270 }
271 void mlirOperationStateAddAttributes(MlirOperationState *state, intptr_t n,
272                                      MlirNamedAttribute const *attributes) {
273   APPEND_ELEMS(MlirNamedAttribute, nAttributes, attributes);
274 }
275 
276 void mlirOperationStateEnableResultTypeInference(MlirOperationState *state) {
277   state->enableResultTypeInference = true;
278 }
279 
280 //===----------------------------------------------------------------------===//
281 // Operation API.
282 //===----------------------------------------------------------------------===//
283 
284 static LogicalResult inferOperationTypes(OperationState &state) {
285   MLIRContext *context = state.getContext();
286   Optional<RegisteredOperationName> info = state.name.getRegisteredInfo();
287   if (!info) {
288     emitError(state.location)
289         << "type inference was requested for the operation " << state.name
290         << ", but the operation was not registered. Ensure that the dialect "
291            "containing the operation is linked into MLIR and registered with "
292            "the context";
293     return failure();
294   }
295 
296   // Fallback to inference via an op interface.
297   auto *inferInterface = info->getInterface<InferTypeOpInterface>();
298   if (!inferInterface) {
299     emitError(state.location)
300         << "type inference was requested for the operation " << state.name
301         << ", but the operation does not support type inference. Result "
302            "types must be specified explicitly.";
303     return failure();
304   }
305 
306   if (succeeded(inferInterface->inferReturnTypes(
307           context, state.location, state.operands,
308           state.attributes.getDictionary(context), state.regions, state.types)))
309     return success();
310 
311   // Diagnostic emitted by interface.
312   return failure();
313 }
314 
315 MlirOperation mlirOperationCreate(MlirOperationState *state) {
316   assert(state);
317   OperationState cppState(unwrap(state->location), unwrap(state->name));
318   SmallVector<Type, 4> resultStorage;
319   SmallVector<Value, 8> operandStorage;
320   SmallVector<Block *, 2> successorStorage;
321   cppState.addTypes(unwrapList(state->nResults, state->results, resultStorage));
322   cppState.addOperands(
323       unwrapList(state->nOperands, state->operands, operandStorage));
324   cppState.addSuccessors(
325       unwrapList(state->nSuccessors, state->successors, successorStorage));
326 
327   cppState.attributes.reserve(state->nAttributes);
328   for (intptr_t i = 0; i < state->nAttributes; ++i)
329     cppState.addAttribute(unwrap(state->attributes[i].name),
330                           unwrap(state->attributes[i].attribute));
331 
332   for (intptr_t i = 0; i < state->nRegions; ++i)
333     cppState.addRegion(std::unique_ptr<Region>(unwrap(state->regions[i])));
334 
335   free(state->results);
336   free(state->operands);
337   free(state->successors);
338   free(state->regions);
339   free(state->attributes);
340 
341   // Infer result types.
342   if (state->enableResultTypeInference) {
343     assert(cppState.types.empty() &&
344            "result type inference enabled and result types provided");
345     if (failed(inferOperationTypes(cppState)))
346       return {nullptr};
347   }
348 
349   MlirOperation result = wrap(Operation::create(cppState));
350   return result;
351 }
352 
353 MlirOperation mlirOperationClone(MlirOperation op) {
354   return wrap(unwrap(op)->clone());
355 }
356 
357 void mlirOperationDestroy(MlirOperation op) { unwrap(op)->erase(); }
358 
359 void mlirOperationRemoveFromParent(MlirOperation op) { unwrap(op)->remove(); }
360 
361 bool mlirOperationEqual(MlirOperation op, MlirOperation other) {
362   return unwrap(op) == unwrap(other);
363 }
364 
365 MlirContext mlirOperationGetContext(MlirOperation op) {
366   return wrap(unwrap(op)->getContext());
367 }
368 
369 MlirLocation mlirOperationGetLocation(MlirOperation op) {
370   return wrap(unwrap(op)->getLoc());
371 }
372 
373 MlirTypeID mlirOperationGetTypeID(MlirOperation op) {
374   if (auto info = unwrap(op)->getRegisteredInfo())
375     return wrap(info->getTypeID());
376   return {nullptr};
377 }
378 
379 MlirIdentifier mlirOperationGetName(MlirOperation op) {
380   return wrap(unwrap(op)->getName().getIdentifier());
381 }
382 
383 MlirBlock mlirOperationGetBlock(MlirOperation op) {
384   return wrap(unwrap(op)->getBlock());
385 }
386 
387 MlirOperation mlirOperationGetParentOperation(MlirOperation op) {
388   return wrap(unwrap(op)->getParentOp());
389 }
390 
391 intptr_t mlirOperationGetNumRegions(MlirOperation op) {
392   return static_cast<intptr_t>(unwrap(op)->getNumRegions());
393 }
394 
395 MlirRegion mlirOperationGetRegion(MlirOperation op, intptr_t pos) {
396   return wrap(&unwrap(op)->getRegion(static_cast<unsigned>(pos)));
397 }
398 
399 MlirRegion mlirOperationGetFirstRegion(MlirOperation op) {
400   Operation *cppOp = unwrap(op);
401   if (cppOp->getNumRegions() == 0)
402     return wrap(static_cast<Region *>(nullptr));
403   return wrap(&cppOp->getRegion(0));
404 }
405 
406 MlirRegion mlirRegionGetNextInOperation(MlirRegion region) {
407   Region *cppRegion = unwrap(region);
408   Operation *parent = cppRegion->getParentOp();
409   intptr_t next = cppRegion->getRegionNumber() + 1;
410   if (parent->getNumRegions() > next)
411     return wrap(&parent->getRegion(next));
412   return wrap(static_cast<Region *>(nullptr));
413 }
414 
415 MlirOperation mlirOperationGetNextInBlock(MlirOperation op) {
416   return wrap(unwrap(op)->getNextNode());
417 }
418 
419 intptr_t mlirOperationGetNumOperands(MlirOperation op) {
420   return static_cast<intptr_t>(unwrap(op)->getNumOperands());
421 }
422 
423 MlirValue mlirOperationGetOperand(MlirOperation op, intptr_t pos) {
424   return wrap(unwrap(op)->getOperand(static_cast<unsigned>(pos)));
425 }
426 
427 void mlirOperationSetOperand(MlirOperation op, intptr_t pos,
428                              MlirValue newValue) {
429   unwrap(op)->setOperand(static_cast<unsigned>(pos), unwrap(newValue));
430 }
431 
432 intptr_t mlirOperationGetNumResults(MlirOperation op) {
433   return static_cast<intptr_t>(unwrap(op)->getNumResults());
434 }
435 
436 MlirValue mlirOperationGetResult(MlirOperation op, intptr_t pos) {
437   return wrap(unwrap(op)->getResult(static_cast<unsigned>(pos)));
438 }
439 
440 intptr_t mlirOperationGetNumSuccessors(MlirOperation op) {
441   return static_cast<intptr_t>(unwrap(op)->getNumSuccessors());
442 }
443 
444 MlirBlock mlirOperationGetSuccessor(MlirOperation op, intptr_t pos) {
445   return wrap(unwrap(op)->getSuccessor(static_cast<unsigned>(pos)));
446 }
447 
448 intptr_t mlirOperationGetNumAttributes(MlirOperation op) {
449   return static_cast<intptr_t>(unwrap(op)->getAttrs().size());
450 }
451 
452 MlirNamedAttribute mlirOperationGetAttribute(MlirOperation op, intptr_t pos) {
453   NamedAttribute attr = unwrap(op)->getAttrs()[pos];
454   return MlirNamedAttribute{wrap(attr.getName()), wrap(attr.getValue())};
455 }
456 
457 MlirAttribute mlirOperationGetAttributeByName(MlirOperation op,
458                                               MlirStringRef name) {
459   return wrap(unwrap(op)->getAttr(unwrap(name)));
460 }
461 
462 void mlirOperationSetAttributeByName(MlirOperation op, MlirStringRef name,
463                                      MlirAttribute attr) {
464   unwrap(op)->setAttr(unwrap(name), unwrap(attr));
465 }
466 
467 bool mlirOperationRemoveAttributeByName(MlirOperation op, MlirStringRef name) {
468   return !!unwrap(op)->removeAttr(unwrap(name));
469 }
470 
471 void mlirOperationPrint(MlirOperation op, MlirStringCallback callback,
472                         void *userData) {
473   detail::CallbackOstream stream(callback, userData);
474   unwrap(op)->print(stream);
475 }
476 
477 void mlirOperationPrintWithFlags(MlirOperation op, MlirOpPrintingFlags flags,
478                                  MlirStringCallback callback, void *userData) {
479   detail::CallbackOstream stream(callback, userData);
480   unwrap(op)->print(stream, *unwrap(flags));
481 }
482 
483 void mlirOperationDump(MlirOperation op) { return unwrap(op)->dump(); }
484 
485 bool mlirOperationVerify(MlirOperation op) {
486   return succeeded(verify(unwrap(op)));
487 }
488 
489 void mlirOperationMoveAfter(MlirOperation op, MlirOperation other) {
490   return unwrap(op)->moveAfter(unwrap(other));
491 }
492 
493 void mlirOperationMoveBefore(MlirOperation op, MlirOperation other) {
494   return unwrap(op)->moveBefore(unwrap(other));
495 }
496 
497 //===----------------------------------------------------------------------===//
498 // Region API.
499 //===----------------------------------------------------------------------===//
500 
501 MlirRegion mlirRegionCreate() { return wrap(new Region); }
502 
503 bool mlirRegionEqual(MlirRegion region, MlirRegion other) {
504   return unwrap(region) == unwrap(other);
505 }
506 
507 MlirBlock mlirRegionGetFirstBlock(MlirRegion region) {
508   Region *cppRegion = unwrap(region);
509   if (cppRegion->empty())
510     return wrap(static_cast<Block *>(nullptr));
511   return wrap(&cppRegion->front());
512 }
513 
514 void mlirRegionAppendOwnedBlock(MlirRegion region, MlirBlock block) {
515   unwrap(region)->push_back(unwrap(block));
516 }
517 
518 void mlirRegionInsertOwnedBlock(MlirRegion region, intptr_t pos,
519                                 MlirBlock block) {
520   auto &blockList = unwrap(region)->getBlocks();
521   blockList.insert(std::next(blockList.begin(), pos), unwrap(block));
522 }
523 
524 void mlirRegionInsertOwnedBlockAfter(MlirRegion region, MlirBlock reference,
525                                      MlirBlock block) {
526   Region *cppRegion = unwrap(region);
527   if (mlirBlockIsNull(reference)) {
528     cppRegion->getBlocks().insert(cppRegion->begin(), unwrap(block));
529     return;
530   }
531 
532   assert(unwrap(reference)->getParent() == unwrap(region) &&
533          "expected reference block to belong to the region");
534   cppRegion->getBlocks().insertAfter(Region::iterator(unwrap(reference)),
535                                      unwrap(block));
536 }
537 
538 void mlirRegionInsertOwnedBlockBefore(MlirRegion region, MlirBlock reference,
539                                       MlirBlock block) {
540   if (mlirBlockIsNull(reference))
541     return mlirRegionAppendOwnedBlock(region, block);
542 
543   assert(unwrap(reference)->getParent() == unwrap(region) &&
544          "expected reference block to belong to the region");
545   unwrap(region)->getBlocks().insert(Region::iterator(unwrap(reference)),
546                                      unwrap(block));
547 }
548 
549 void mlirRegionDestroy(MlirRegion region) {
550   delete static_cast<Region *>(region.ptr);
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // Block API.
555 //===----------------------------------------------------------------------===//
556 
557 MlirBlock mlirBlockCreate(intptr_t nArgs, MlirType const *args,
558                           MlirLocation const *locs) {
559   Block *b = new Block;
560   for (intptr_t i = 0; i < nArgs; ++i)
561     b->addArgument(unwrap(args[i]), unwrap(locs[i]));
562   return wrap(b);
563 }
564 
565 bool mlirBlockEqual(MlirBlock block, MlirBlock other) {
566   return unwrap(block) == unwrap(other);
567 }
568 
569 MlirOperation mlirBlockGetParentOperation(MlirBlock block) {
570   return wrap(unwrap(block)->getParentOp());
571 }
572 
573 MlirRegion mlirBlockGetParentRegion(MlirBlock block) {
574   return wrap(unwrap(block)->getParent());
575 }
576 
577 MlirBlock mlirBlockGetNextInRegion(MlirBlock block) {
578   return wrap(unwrap(block)->getNextNode());
579 }
580 
581 MlirOperation mlirBlockGetFirstOperation(MlirBlock block) {
582   Block *cppBlock = unwrap(block);
583   if (cppBlock->empty())
584     return wrap(static_cast<Operation *>(nullptr));
585   return wrap(&cppBlock->front());
586 }
587 
588 MlirOperation mlirBlockGetTerminator(MlirBlock block) {
589   Block *cppBlock = unwrap(block);
590   if (cppBlock->empty())
591     return wrap(static_cast<Operation *>(nullptr));
592   Operation &back = cppBlock->back();
593   if (!back.hasTrait<OpTrait::IsTerminator>())
594     return wrap(static_cast<Operation *>(nullptr));
595   return wrap(&back);
596 }
597 
598 void mlirBlockAppendOwnedOperation(MlirBlock block, MlirOperation operation) {
599   unwrap(block)->push_back(unwrap(operation));
600 }
601 
602 void mlirBlockInsertOwnedOperation(MlirBlock block, intptr_t pos,
603                                    MlirOperation operation) {
604   auto &opList = unwrap(block)->getOperations();
605   opList.insert(std::next(opList.begin(), pos), unwrap(operation));
606 }
607 
608 void mlirBlockInsertOwnedOperationAfter(MlirBlock block,
609                                         MlirOperation reference,
610                                         MlirOperation operation) {
611   Block *cppBlock = unwrap(block);
612   if (mlirOperationIsNull(reference)) {
613     cppBlock->getOperations().insert(cppBlock->begin(), unwrap(operation));
614     return;
615   }
616 
617   assert(unwrap(reference)->getBlock() == unwrap(block) &&
618          "expected reference operation to belong to the block");
619   cppBlock->getOperations().insertAfter(Block::iterator(unwrap(reference)),
620                                         unwrap(operation));
621 }
622 
623 void mlirBlockInsertOwnedOperationBefore(MlirBlock block,
624                                          MlirOperation reference,
625                                          MlirOperation operation) {
626   if (mlirOperationIsNull(reference))
627     return mlirBlockAppendOwnedOperation(block, operation);
628 
629   assert(unwrap(reference)->getBlock() == unwrap(block) &&
630          "expected reference operation to belong to the block");
631   unwrap(block)->getOperations().insert(Block::iterator(unwrap(reference)),
632                                         unwrap(operation));
633 }
634 
635 void mlirBlockDestroy(MlirBlock block) { delete unwrap(block); }
636 
637 void mlirBlockDetach(MlirBlock block) {
638   Block *b = unwrap(block);
639   b->getParent()->getBlocks().remove(b);
640 }
641 
642 intptr_t mlirBlockGetNumArguments(MlirBlock block) {
643   return static_cast<intptr_t>(unwrap(block)->getNumArguments());
644 }
645 
646 MlirValue mlirBlockAddArgument(MlirBlock block, MlirType type,
647                                MlirLocation loc) {
648   return wrap(unwrap(block)->addArgument(unwrap(type), unwrap(loc)));
649 }
650 
651 MlirValue mlirBlockGetArgument(MlirBlock block, intptr_t pos) {
652   return wrap(unwrap(block)->getArgument(static_cast<unsigned>(pos)));
653 }
654 
655 void mlirBlockPrint(MlirBlock block, MlirStringCallback callback,
656                     void *userData) {
657   detail::CallbackOstream stream(callback, userData);
658   unwrap(block)->print(stream);
659 }
660 
661 //===----------------------------------------------------------------------===//
662 // Value API.
663 //===----------------------------------------------------------------------===//
664 
665 bool mlirValueEqual(MlirValue value1, MlirValue value2) {
666   return unwrap(value1) == unwrap(value2);
667 }
668 
669 bool mlirValueIsABlockArgument(MlirValue value) {
670   return unwrap(value).isa<BlockArgument>();
671 }
672 
673 bool mlirValueIsAOpResult(MlirValue value) {
674   return unwrap(value).isa<OpResult>();
675 }
676 
677 MlirBlock mlirBlockArgumentGetOwner(MlirValue value) {
678   return wrap(unwrap(value).cast<BlockArgument>().getOwner());
679 }
680 
681 intptr_t mlirBlockArgumentGetArgNumber(MlirValue value) {
682   return static_cast<intptr_t>(
683       unwrap(value).cast<BlockArgument>().getArgNumber());
684 }
685 
686 void mlirBlockArgumentSetType(MlirValue value, MlirType type) {
687   unwrap(value).cast<BlockArgument>().setType(unwrap(type));
688 }
689 
690 MlirOperation mlirOpResultGetOwner(MlirValue value) {
691   return wrap(unwrap(value).cast<OpResult>().getOwner());
692 }
693 
694 intptr_t mlirOpResultGetResultNumber(MlirValue value) {
695   return static_cast<intptr_t>(
696       unwrap(value).cast<OpResult>().getResultNumber());
697 }
698 
699 MlirType mlirValueGetType(MlirValue value) {
700   return wrap(unwrap(value).getType());
701 }
702 
703 void mlirValueDump(MlirValue value) { unwrap(value).dump(); }
704 
705 void mlirValuePrint(MlirValue value, MlirStringCallback callback,
706                     void *userData) {
707   detail::CallbackOstream stream(callback, userData);
708   unwrap(value).print(stream);
709 }
710 
711 //===----------------------------------------------------------------------===//
712 // Type API.
713 //===----------------------------------------------------------------------===//
714 
715 MlirType mlirTypeParseGet(MlirContext context, MlirStringRef type) {
716   return wrap(mlir::parseType(unwrap(type), unwrap(context)));
717 }
718 
719 MlirContext mlirTypeGetContext(MlirType type) {
720   return wrap(unwrap(type).getContext());
721 }
722 
723 MlirTypeID mlirTypeGetTypeID(MlirType type) {
724   return wrap(unwrap(type).getTypeID());
725 }
726 
727 bool mlirTypeEqual(MlirType t1, MlirType t2) {
728   return unwrap(t1) == unwrap(t2);
729 }
730 
731 void mlirTypePrint(MlirType type, MlirStringCallback callback, void *userData) {
732   detail::CallbackOstream stream(callback, userData);
733   unwrap(type).print(stream);
734 }
735 
736 void mlirTypeDump(MlirType type) { unwrap(type).dump(); }
737 
738 //===----------------------------------------------------------------------===//
739 // Attribute API.
740 //===----------------------------------------------------------------------===//
741 
742 MlirAttribute mlirAttributeParseGet(MlirContext context, MlirStringRef attr) {
743   return wrap(mlir::parseAttribute(unwrap(attr), unwrap(context)));
744 }
745 
746 MlirContext mlirAttributeGetContext(MlirAttribute attribute) {
747   return wrap(unwrap(attribute).getContext());
748 }
749 
750 MlirType mlirAttributeGetType(MlirAttribute attribute) {
751   return wrap(unwrap(attribute).getType());
752 }
753 
754 MlirTypeID mlirAttributeGetTypeID(MlirAttribute attr) {
755   return wrap(unwrap(attr).getTypeID());
756 }
757 
758 bool mlirAttributeEqual(MlirAttribute a1, MlirAttribute a2) {
759   return unwrap(a1) == unwrap(a2);
760 }
761 
762 void mlirAttributePrint(MlirAttribute attr, MlirStringCallback callback,
763                         void *userData) {
764   detail::CallbackOstream stream(callback, userData);
765   unwrap(attr).print(stream);
766 }
767 
768 void mlirAttributeDump(MlirAttribute attr) { unwrap(attr).dump(); }
769 
770 MlirNamedAttribute mlirNamedAttributeGet(MlirIdentifier name,
771                                          MlirAttribute attr) {
772   return MlirNamedAttribute{name, attr};
773 }
774 
775 //===----------------------------------------------------------------------===//
776 // Identifier API.
777 //===----------------------------------------------------------------------===//
778 
779 MlirIdentifier mlirIdentifierGet(MlirContext context, MlirStringRef str) {
780   return wrap(StringAttr::get(unwrap(context), unwrap(str)));
781 }
782 
783 MlirContext mlirIdentifierGetContext(MlirIdentifier ident) {
784   return wrap(unwrap(ident).getContext());
785 }
786 
787 bool mlirIdentifierEqual(MlirIdentifier ident, MlirIdentifier other) {
788   return unwrap(ident) == unwrap(other);
789 }
790 
791 MlirStringRef mlirIdentifierStr(MlirIdentifier ident) {
792   return wrap(unwrap(ident).strref());
793 }
794 
795 //===----------------------------------------------------------------------===//
796 // Symbol and SymbolTable API.
797 //===----------------------------------------------------------------------===//
798 
799 MlirStringRef mlirSymbolTableGetSymbolAttributeName() {
800   return wrap(SymbolTable::getSymbolAttrName());
801 }
802 
803 MlirStringRef mlirSymbolTableGetVisibilityAttributeName() {
804   return wrap(SymbolTable::getVisibilityAttrName());
805 }
806 
807 MlirSymbolTable mlirSymbolTableCreate(MlirOperation operation) {
808   if (!unwrap(operation)->hasTrait<OpTrait::SymbolTable>())
809     return wrap(static_cast<SymbolTable *>(nullptr));
810   return wrap(new SymbolTable(unwrap(operation)));
811 }
812 
813 void mlirSymbolTableDestroy(MlirSymbolTable symbolTable) {
814   delete unwrap(symbolTable);
815 }
816 
817 MlirOperation mlirSymbolTableLookup(MlirSymbolTable symbolTable,
818                                     MlirStringRef name) {
819   return wrap(unwrap(symbolTable)->lookup(StringRef(name.data, name.length)));
820 }
821 
822 MlirAttribute mlirSymbolTableInsert(MlirSymbolTable symbolTable,
823                                     MlirOperation operation) {
824   return wrap((Attribute)unwrap(symbolTable)->insert(unwrap(operation)));
825 }
826 
827 void mlirSymbolTableErase(MlirSymbolTable symbolTable,
828                           MlirOperation operation) {
829   unwrap(symbolTable)->erase(unwrap(operation));
830 }
831 
832 MlirLogicalResult mlirSymbolTableReplaceAllSymbolUses(MlirStringRef oldSymbol,
833                                                       MlirStringRef newSymbol,
834                                                       MlirOperation from) {
835   auto *cppFrom = unwrap(from);
836   auto *context = cppFrom->getContext();
837   auto oldSymbolAttr = StringAttr::get(context, unwrap(oldSymbol));
838   auto newSymbolAttr = StringAttr::get(context, unwrap(newSymbol));
839   return wrap(SymbolTable::replaceAllSymbolUses(oldSymbolAttr, newSymbolAttr,
840                                                 unwrap(from)));
841 }
842 
843 void mlirSymbolTableWalkSymbolTables(MlirOperation from, bool allSymUsesVisible,
844                                      void (*callback)(MlirOperation, bool,
845                                                       void *userData),
846                                      void *userData) {
847   SymbolTable::walkSymbolTables(unwrap(from), allSymUsesVisible,
848                                 [&](Operation *foundOpCpp, bool isVisible) {
849                                   callback(wrap(foundOpCpp), isVisible,
850                                            userData);
851                                 });
852 }
853