xref: /llvm-project-15.0.7/mlir/test/CAPI/ir.c (revision 09cebfb9)
1 //===- ir.c - Simple test of C APIs ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM
4 // Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 /* RUN: mlir-capi-ir-test 2>&1 | FileCheck %s
11  */
12 
13 #include "mlir-c/IR.h"
14 #include "mlir-c/AffineExpr.h"
15 #include "mlir-c/AffineMap.h"
16 #include "mlir-c/BuiltinAttributes.h"
17 #include "mlir-c/BuiltinTypes.h"
18 #include "mlir-c/Diagnostics.h"
19 #include "mlir-c/Dialect/Func.h"
20 #include "mlir-c/IntegerSet.h"
21 #include "mlir-c/RegisterEverything.h"
22 #include "mlir-c/Support.h"
23 
24 #include <assert.h>
25 #include <inttypes.h>
26 #include <math.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 
31 static void registerAllUpstreamDialects(MlirContext ctx) {
32   MlirDialectRegistry registry = mlirDialectRegistryCreate();
33   mlirRegisterAllDialects(registry);
34   mlirContextAppendDialectRegistry(ctx, registry);
35   mlirDialectRegistryDestroy(registry);
36 }
37 
38 void populateLoopBody(MlirContext ctx, MlirBlock loopBody,
39                       MlirLocation location, MlirBlock funcBody) {
40   MlirValue iv = mlirBlockGetArgument(loopBody, 0);
41   MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
42   MlirValue funcArg1 = mlirBlockGetArgument(funcBody, 1);
43   MlirType f32Type =
44       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("f32"));
45 
46   MlirOperationState loadLHSState = mlirOperationStateGet(
47       mlirStringRefCreateFromCString("memref.load"), location);
48   MlirValue loadLHSOperands[] = {funcArg0, iv};
49   mlirOperationStateAddOperands(&loadLHSState, 2, loadLHSOperands);
50   mlirOperationStateAddResults(&loadLHSState, 1, &f32Type);
51   MlirOperation loadLHS = mlirOperationCreate(&loadLHSState);
52   mlirBlockAppendOwnedOperation(loopBody, loadLHS);
53 
54   MlirOperationState loadRHSState = mlirOperationStateGet(
55       mlirStringRefCreateFromCString("memref.load"), location);
56   MlirValue loadRHSOperands[] = {funcArg1, iv};
57   mlirOperationStateAddOperands(&loadRHSState, 2, loadRHSOperands);
58   mlirOperationStateAddResults(&loadRHSState, 1, &f32Type);
59   MlirOperation loadRHS = mlirOperationCreate(&loadRHSState);
60   mlirBlockAppendOwnedOperation(loopBody, loadRHS);
61 
62   MlirOperationState addState = mlirOperationStateGet(
63       mlirStringRefCreateFromCString("arith.addf"), location);
64   MlirValue addOperands[] = {mlirOperationGetResult(loadLHS, 0),
65                              mlirOperationGetResult(loadRHS, 0)};
66   mlirOperationStateAddOperands(&addState, 2, addOperands);
67   mlirOperationStateAddResults(&addState, 1, &f32Type);
68   MlirOperation add = mlirOperationCreate(&addState);
69   mlirBlockAppendOwnedOperation(loopBody, add);
70 
71   MlirOperationState storeState = mlirOperationStateGet(
72       mlirStringRefCreateFromCString("memref.store"), location);
73   MlirValue storeOperands[] = {mlirOperationGetResult(add, 0), funcArg0, iv};
74   mlirOperationStateAddOperands(&storeState, 3, storeOperands);
75   MlirOperation store = mlirOperationCreate(&storeState);
76   mlirBlockAppendOwnedOperation(loopBody, store);
77 
78   MlirOperationState yieldState = mlirOperationStateGet(
79       mlirStringRefCreateFromCString("scf.yield"), location);
80   MlirOperation yield = mlirOperationCreate(&yieldState);
81   mlirBlockAppendOwnedOperation(loopBody, yield);
82 }
83 
84 MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) {
85   MlirModule moduleOp = mlirModuleCreateEmpty(location);
86   MlirBlock moduleBody = mlirModuleGetBody(moduleOp);
87 
88   MlirType memrefType =
89       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("memref<?xf32>"));
90   MlirType funcBodyArgTypes[] = {memrefType, memrefType};
91   MlirLocation funcBodyArgLocs[] = {location, location};
92   MlirRegion funcBodyRegion = mlirRegionCreate();
93   MlirBlock funcBody =
94       mlirBlockCreate(sizeof(funcBodyArgTypes) / sizeof(MlirType),
95                       funcBodyArgTypes, funcBodyArgLocs);
96   mlirRegionAppendOwnedBlock(funcBodyRegion, funcBody);
97 
98   MlirAttribute funcTypeAttr = mlirAttributeParseGet(
99       ctx,
100       mlirStringRefCreateFromCString("(memref<?xf32>, memref<?xf32>) -> ()"));
101   MlirAttribute funcNameAttr =
102       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("\"add\""));
103   MlirNamedAttribute funcAttrs[] = {
104       mlirNamedAttributeGet(
105           mlirIdentifierGet(ctx,
106                             mlirStringRefCreateFromCString("function_type")),
107           funcTypeAttr),
108       mlirNamedAttributeGet(
109           mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("sym_name")),
110           funcNameAttr)};
111   MlirOperationState funcState = mlirOperationStateGet(
112       mlirStringRefCreateFromCString("func.func"), location);
113   mlirOperationStateAddAttributes(&funcState, 2, funcAttrs);
114   mlirOperationStateAddOwnedRegions(&funcState, 1, &funcBodyRegion);
115   MlirOperation func = mlirOperationCreate(&funcState);
116   mlirBlockInsertOwnedOperation(moduleBody, 0, func);
117 
118   MlirType indexType =
119       mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("index"));
120   MlirAttribute indexZeroLiteral =
121       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
122   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
123       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
124       indexZeroLiteral);
125   MlirOperationState constZeroState = mlirOperationStateGet(
126       mlirStringRefCreateFromCString("arith.constant"), location);
127   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
128   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
129   MlirOperation constZero = mlirOperationCreate(&constZeroState);
130   mlirBlockAppendOwnedOperation(funcBody, constZero);
131 
132   MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
133   MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);
134   MlirValue dimOperands[] = {funcArg0, constZeroValue};
135   MlirOperationState dimState = mlirOperationStateGet(
136       mlirStringRefCreateFromCString("memref.dim"), location);
137   mlirOperationStateAddOperands(&dimState, 2, dimOperands);
138   mlirOperationStateAddResults(&dimState, 1, &indexType);
139   MlirOperation dim = mlirOperationCreate(&dimState);
140   mlirBlockAppendOwnedOperation(funcBody, dim);
141 
142   MlirRegion loopBodyRegion = mlirRegionCreate();
143   MlirBlock loopBody = mlirBlockCreate(0, NULL, NULL);
144   mlirBlockAddArgument(loopBody, indexType, location);
145   mlirRegionAppendOwnedBlock(loopBodyRegion, loopBody);
146 
147   MlirAttribute indexOneLiteral =
148       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
149   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
150       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
151       indexOneLiteral);
152   MlirOperationState constOneState = mlirOperationStateGet(
153       mlirStringRefCreateFromCString("arith.constant"), location);
154   mlirOperationStateAddResults(&constOneState, 1, &indexType);
155   mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
156   MlirOperation constOne = mlirOperationCreate(&constOneState);
157   mlirBlockAppendOwnedOperation(funcBody, constOne);
158 
159   MlirValue dimValue = mlirOperationGetResult(dim, 0);
160   MlirValue constOneValue = mlirOperationGetResult(constOne, 0);
161   MlirValue loopOperands[] = {constZeroValue, dimValue, constOneValue};
162   MlirOperationState loopState = mlirOperationStateGet(
163       mlirStringRefCreateFromCString("scf.for"), location);
164   mlirOperationStateAddOperands(&loopState, 3, loopOperands);
165   mlirOperationStateAddOwnedRegions(&loopState, 1, &loopBodyRegion);
166   MlirOperation loop = mlirOperationCreate(&loopState);
167   mlirBlockAppendOwnedOperation(funcBody, loop);
168 
169   populateLoopBody(ctx, loopBody, location, funcBody);
170 
171   MlirOperationState retState = mlirOperationStateGet(
172       mlirStringRefCreateFromCString("func.return"), location);
173   MlirOperation ret = mlirOperationCreate(&retState);
174   mlirBlockAppendOwnedOperation(funcBody, ret);
175 
176   MlirOperation module = mlirModuleGetOperation(moduleOp);
177   mlirOperationDump(module);
178   // clang-format off
179   // CHECK: module {
180   // CHECK:   func @add(%[[ARG0:.*]]: memref<?xf32>, %[[ARG1:.*]]: memref<?xf32>) {
181   // CHECK:     %[[C0:.*]] = arith.constant 0 : index
182   // CHECK:     %[[DIM:.*]] = memref.dim %[[ARG0]], %[[C0]] : memref<?xf32>
183   // CHECK:     %[[C1:.*]] = arith.constant 1 : index
184   // CHECK:     scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
185   // CHECK:       %[[LHS:.*]] = memref.load %[[ARG0]][%[[I]]] : memref<?xf32>
186   // CHECK:       %[[RHS:.*]] = memref.load %[[ARG1]][%[[I]]] : memref<?xf32>
187   // CHECK:       %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
188   // CHECK:       memref.store %[[SUM]], %[[ARG0]][%[[I]]] : memref<?xf32>
189   // CHECK:     }
190   // CHECK:     return
191   // CHECK:   }
192   // CHECK: }
193   // clang-format on
194 
195   return moduleOp;
196 }
197 
198 struct OpListNode {
199   MlirOperation op;
200   struct OpListNode *next;
201 };
202 typedef struct OpListNode OpListNode;
203 
204 struct ModuleStats {
205   unsigned numOperations;
206   unsigned numAttributes;
207   unsigned numBlocks;
208   unsigned numRegions;
209   unsigned numValues;
210   unsigned numBlockArguments;
211   unsigned numOpResults;
212 };
213 typedef struct ModuleStats ModuleStats;
214 
215 int collectStatsSingle(OpListNode *head, ModuleStats *stats) {
216   MlirOperation operation = head->op;
217   stats->numOperations += 1;
218   stats->numValues += mlirOperationGetNumResults(operation);
219   stats->numAttributes += mlirOperationGetNumAttributes(operation);
220 
221   unsigned numRegions = mlirOperationGetNumRegions(operation);
222 
223   stats->numRegions += numRegions;
224 
225   intptr_t numResults = mlirOperationGetNumResults(operation);
226   for (intptr_t i = 0; i < numResults; ++i) {
227     MlirValue result = mlirOperationGetResult(operation, i);
228     if (!mlirValueIsAOpResult(result))
229       return 1;
230     if (mlirValueIsABlockArgument(result))
231       return 2;
232     if (!mlirOperationEqual(operation, mlirOpResultGetOwner(result)))
233       return 3;
234     if (i != mlirOpResultGetResultNumber(result))
235       return 4;
236     ++stats->numOpResults;
237   }
238 
239   MlirRegion region = mlirOperationGetFirstRegion(operation);
240   while (!mlirRegionIsNull(region)) {
241     for (MlirBlock block = mlirRegionGetFirstBlock(region);
242          !mlirBlockIsNull(block); block = mlirBlockGetNextInRegion(block)) {
243       ++stats->numBlocks;
244       intptr_t numArgs = mlirBlockGetNumArguments(block);
245       stats->numValues += numArgs;
246       for (intptr_t j = 0; j < numArgs; ++j) {
247         MlirValue arg = mlirBlockGetArgument(block, j);
248         if (!mlirValueIsABlockArgument(arg))
249           return 5;
250         if (mlirValueIsAOpResult(arg))
251           return 6;
252         if (!mlirBlockEqual(block, mlirBlockArgumentGetOwner(arg)))
253           return 7;
254         if (j != mlirBlockArgumentGetArgNumber(arg))
255           return 8;
256         ++stats->numBlockArguments;
257       }
258 
259       for (MlirOperation child = mlirBlockGetFirstOperation(block);
260            !mlirOperationIsNull(child);
261            child = mlirOperationGetNextInBlock(child)) {
262         OpListNode *node = malloc(sizeof(OpListNode));
263         node->op = child;
264         node->next = head->next;
265         head->next = node;
266       }
267     }
268     region = mlirRegionGetNextInOperation(region);
269   }
270   return 0;
271 }
272 
273 int collectStats(MlirOperation operation) {
274   OpListNode *head = malloc(sizeof(OpListNode));
275   head->op = operation;
276   head->next = NULL;
277 
278   ModuleStats stats;
279   stats.numOperations = 0;
280   stats.numAttributes = 0;
281   stats.numBlocks = 0;
282   stats.numRegions = 0;
283   stats.numValues = 0;
284   stats.numBlockArguments = 0;
285   stats.numOpResults = 0;
286 
287   do {
288     int retval = collectStatsSingle(head, &stats);
289     if (retval) {
290       free(head);
291       return retval;
292     }
293     OpListNode *next = head->next;
294     free(head);
295     head = next;
296   } while (head);
297 
298   if (stats.numValues != stats.numBlockArguments + stats.numOpResults)
299     return 100;
300 
301   fprintf(stderr, "@stats\n");
302   fprintf(stderr, "Number of operations: %u\n", stats.numOperations);
303   fprintf(stderr, "Number of attributes: %u\n", stats.numAttributes);
304   fprintf(stderr, "Number of blocks: %u\n", stats.numBlocks);
305   fprintf(stderr, "Number of regions: %u\n", stats.numRegions);
306   fprintf(stderr, "Number of values: %u\n", stats.numValues);
307   fprintf(stderr, "Number of block arguments: %u\n", stats.numBlockArguments);
308   fprintf(stderr, "Number of op results: %u\n", stats.numOpResults);
309   // clang-format off
310   // CHECK-LABEL: @stats
311   // CHECK: Number of operations: 12
312   // CHECK: Number of attributes: 4
313   // CHECK: Number of blocks: 3
314   // CHECK: Number of regions: 3
315   // CHECK: Number of values: 9
316   // CHECK: Number of block arguments: 3
317   // CHECK: Number of op results: 6
318   // clang-format on
319   return 0;
320 }
321 
322 static void printToStderr(MlirStringRef str, void *userData) {
323   (void)userData;
324   fwrite(str.data, 1, str.length, stderr);
325 }
326 
327 static void printFirstOfEach(MlirContext ctx, MlirOperation operation) {
328   // Assuming we are given a module, go to the first operation of the first
329   // function.
330   MlirRegion region = mlirOperationGetRegion(operation, 0);
331   MlirBlock block = mlirRegionGetFirstBlock(region);
332   operation = mlirBlockGetFirstOperation(block);
333   region = mlirOperationGetRegion(operation, 0);
334   MlirOperation parentOperation = operation;
335   block = mlirRegionGetFirstBlock(region);
336   operation = mlirBlockGetFirstOperation(block);
337   assert(mlirModuleIsNull(mlirModuleFromOperation(operation)));
338 
339   // Verify that parent operation and block report correctly.
340   // CHECK: Parent operation eq: 1
341   fprintf(stderr, "Parent operation eq: %d\n",
342           mlirOperationEqual(mlirOperationGetParentOperation(operation),
343                              parentOperation));
344   // CHECK: Block eq: 1
345   fprintf(stderr, "Block eq: %d\n",
346           mlirBlockEqual(mlirOperationGetBlock(operation), block));
347   // CHECK: Block parent operation eq: 1
348   fprintf(
349       stderr, "Block parent operation eq: %d\n",
350       mlirOperationEqual(mlirBlockGetParentOperation(block), parentOperation));
351   // CHECK: Block parent region eq: 1
352   fprintf(stderr, "Block parent region eq: %d\n",
353           mlirRegionEqual(mlirBlockGetParentRegion(block), region));
354 
355   // In the module we created, the first operation of the first function is
356   // an "memref.dim", which has an attribute and a single result that we can
357   // use to test the printing mechanism.
358   mlirBlockPrint(block, printToStderr, NULL);
359   fprintf(stderr, "\n");
360   fprintf(stderr, "First operation: ");
361   mlirOperationPrint(operation, printToStderr, NULL);
362   fprintf(stderr, "\n");
363   // clang-format off
364   // CHECK:   %[[C0:.*]] = arith.constant 0 : index
365   // CHECK:   %[[DIM:.*]] = memref.dim %{{.*}}, %[[C0]] : memref<?xf32>
366   // CHECK:   %[[C1:.*]] = arith.constant 1 : index
367   // CHECK:   scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
368   // CHECK:     %[[LHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
369   // CHECK:     %[[RHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
370   // CHECK:     %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
371   // CHECK:     memref.store %[[SUM]], %{{.*}}[%[[I]]] : memref<?xf32>
372   // CHECK:   }
373   // CHECK: return
374   // CHECK: First operation: {{.*}} = arith.constant 0 : index
375   // clang-format on
376 
377   // Get the operation name and print it.
378   MlirIdentifier ident = mlirOperationGetName(operation);
379   MlirStringRef identStr = mlirIdentifierStr(ident);
380   fprintf(stderr, "Operation name: '");
381   for (size_t i = 0; i < identStr.length; ++i)
382     fputc(identStr.data[i], stderr);
383   fprintf(stderr, "'\n");
384   // CHECK: Operation name: 'arith.constant'
385 
386   // Get the identifier again and verify equal.
387   MlirIdentifier identAgain = mlirIdentifierGet(ctx, identStr);
388   fprintf(stderr, "Identifier equal: %d\n",
389           mlirIdentifierEqual(ident, identAgain));
390   // CHECK: Identifier equal: 1
391 
392   // Get the block terminator and print it.
393   MlirOperation terminator = mlirBlockGetTerminator(block);
394   fprintf(stderr, "Terminator: ");
395   mlirOperationPrint(terminator, printToStderr, NULL);
396   fprintf(stderr, "\n");
397   // CHECK: Terminator: func.return
398 
399   // Get the attribute by index.
400   MlirNamedAttribute namedAttr0 = mlirOperationGetAttribute(operation, 0);
401   fprintf(stderr, "Get attr 0: ");
402   mlirAttributePrint(namedAttr0.attribute, printToStderr, NULL);
403   fprintf(stderr, "\n");
404   // CHECK: Get attr 0: 0 : index
405 
406   // Now re-get the attribute by name.
407   MlirAttribute attr0ByName = mlirOperationGetAttributeByName(
408       operation, mlirIdentifierStr(namedAttr0.name));
409   fprintf(stderr, "Get attr 0 by name: ");
410   mlirAttributePrint(attr0ByName, printToStderr, NULL);
411   fprintf(stderr, "\n");
412   // CHECK: Get attr 0 by name: 0 : index
413 
414   // Get a non-existing attribute and assert that it is null (sanity).
415   fprintf(stderr, "does_not_exist is null: %d\n",
416           mlirAttributeIsNull(mlirOperationGetAttributeByName(
417               operation, mlirStringRefCreateFromCString("does_not_exist"))));
418   // CHECK: does_not_exist is null: 1
419 
420   // Get result 0 and its type.
421   MlirValue value = mlirOperationGetResult(operation, 0);
422   fprintf(stderr, "Result 0: ");
423   mlirValuePrint(value, printToStderr, NULL);
424   fprintf(stderr, "\n");
425   fprintf(stderr, "Value is null: %d\n", mlirValueIsNull(value));
426   // CHECK: Result 0: {{.*}} = arith.constant 0 : index
427   // CHECK: Value is null: 0
428 
429   MlirType type = mlirValueGetType(value);
430   fprintf(stderr, "Result 0 type: ");
431   mlirTypePrint(type, printToStderr, NULL);
432   fprintf(stderr, "\n");
433   // CHECK: Result 0 type: index
434 
435   // Set a custom attribute.
436   mlirOperationSetAttributeByName(operation,
437                                   mlirStringRefCreateFromCString("custom_attr"),
438                                   mlirBoolAttrGet(ctx, 1));
439   fprintf(stderr, "Op with set attr: ");
440   mlirOperationPrint(operation, printToStderr, NULL);
441   fprintf(stderr, "\n");
442   // CHECK: Op with set attr: {{.*}} {custom_attr = true}
443 
444   // Remove the attribute.
445   fprintf(stderr, "Remove attr: %d\n",
446           mlirOperationRemoveAttributeByName(
447               operation, mlirStringRefCreateFromCString("custom_attr")));
448   fprintf(stderr, "Remove attr again: %d\n",
449           mlirOperationRemoveAttributeByName(
450               operation, mlirStringRefCreateFromCString("custom_attr")));
451   fprintf(stderr, "Removed attr is null: %d\n",
452           mlirAttributeIsNull(mlirOperationGetAttributeByName(
453               operation, mlirStringRefCreateFromCString("custom_attr"))));
454   // CHECK: Remove attr: 1
455   // CHECK: Remove attr again: 0
456   // CHECK: Removed attr is null: 1
457 
458   // Add a large attribute to verify printing flags.
459   int64_t eltsShape[] = {4};
460   int32_t eltsData[] = {1, 2, 3, 4};
461   mlirOperationSetAttributeByName(
462       operation, mlirStringRefCreateFromCString("elts"),
463       mlirDenseElementsAttrInt32Get(
464           mlirRankedTensorTypeGet(1, eltsShape, mlirIntegerTypeGet(ctx, 32),
465                                   mlirAttributeGetNull()),
466           4, eltsData));
467   MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate();
468   mlirOpPrintingFlagsElideLargeElementsAttrs(flags, 2);
469   mlirOpPrintingFlagsPrintGenericOpForm(flags);
470   mlirOpPrintingFlagsEnableDebugInfo(flags, /*prettyForm=*/0);
471   mlirOpPrintingFlagsUseLocalScope(flags);
472   fprintf(stderr, "Op print with all flags: ");
473   mlirOperationPrintWithFlags(operation, flags, printToStderr, NULL);
474   fprintf(stderr, "\n");
475   // clang-format off
476   // CHECK: Op print with all flags: %{{.*}} = "arith.constant"() {elts = opaque<"elided_large_const", "0xDEADBEEF"> : tensor<4xi32>, value = 0 : index} : () -> index loc(unknown)
477   // clang-format on
478 
479   mlirOpPrintingFlagsDestroy(flags);
480 }
481 
482 static int constructAndTraverseIr(MlirContext ctx) {
483   MlirLocation location = mlirLocationUnknownGet(ctx);
484 
485   MlirModule moduleOp = makeAndDumpAdd(ctx, location);
486   MlirOperation module = mlirModuleGetOperation(moduleOp);
487   assert(!mlirModuleIsNull(mlirModuleFromOperation(module)));
488 
489   int errcode = collectStats(module);
490   if (errcode)
491     return errcode;
492 
493   printFirstOfEach(ctx, module);
494 
495   mlirModuleDestroy(moduleOp);
496   return 0;
497 }
498 
499 /// Creates an operation with a region containing multiple blocks with
500 /// operations and dumps it. The blocks and operations are inserted using
501 /// block/operation-relative API and their final order is checked.
502 static void buildWithInsertionsAndPrint(MlirContext ctx) {
503   MlirLocation loc = mlirLocationUnknownGet(ctx);
504   mlirContextSetAllowUnregisteredDialects(ctx, true);
505 
506   MlirRegion owningRegion = mlirRegionCreate();
507   MlirBlock nullBlock = mlirRegionGetFirstBlock(owningRegion);
508   MlirOperationState state = mlirOperationStateGet(
509       mlirStringRefCreateFromCString("insertion.order.test"), loc);
510   mlirOperationStateAddOwnedRegions(&state, 1, &owningRegion);
511   MlirOperation op = mlirOperationCreate(&state);
512   MlirRegion region = mlirOperationGetRegion(op, 0);
513 
514   // Use integer types of different bitwidth as block arguments in order to
515   // differentiate blocks.
516   MlirType i1 = mlirIntegerTypeGet(ctx, 1);
517   MlirType i2 = mlirIntegerTypeGet(ctx, 2);
518   MlirType i3 = mlirIntegerTypeGet(ctx, 3);
519   MlirType i4 = mlirIntegerTypeGet(ctx, 4);
520   MlirType i5 = mlirIntegerTypeGet(ctx, 5);
521   MlirBlock block1 = mlirBlockCreate(1, &i1, &loc);
522   MlirBlock block2 = mlirBlockCreate(1, &i2, &loc);
523   MlirBlock block3 = mlirBlockCreate(1, &i3, &loc);
524   MlirBlock block4 = mlirBlockCreate(1, &i4, &loc);
525   MlirBlock block5 = mlirBlockCreate(1, &i5, &loc);
526   // Insert blocks so as to obtain the 1-2-3-4 order,
527   mlirRegionInsertOwnedBlockBefore(region, nullBlock, block3);
528   mlirRegionInsertOwnedBlockBefore(region, block3, block2);
529   mlirRegionInsertOwnedBlockAfter(region, nullBlock, block1);
530   mlirRegionInsertOwnedBlockAfter(region, block3, block4);
531   mlirRegionInsertOwnedBlockBefore(region, block3, block5);
532 
533   MlirOperationState op1State =
534       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op1"), loc);
535   MlirOperationState op2State =
536       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op2"), loc);
537   MlirOperationState op3State =
538       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op3"), loc);
539   MlirOperationState op4State =
540       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op4"), loc);
541   MlirOperationState op5State =
542       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op5"), loc);
543   MlirOperationState op6State =
544       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op6"), loc);
545   MlirOperationState op7State =
546       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op7"), loc);
547   MlirOperationState op8State =
548       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op8"), loc);
549   MlirOperation op1 = mlirOperationCreate(&op1State);
550   MlirOperation op2 = mlirOperationCreate(&op2State);
551   MlirOperation op3 = mlirOperationCreate(&op3State);
552   MlirOperation op4 = mlirOperationCreate(&op4State);
553   MlirOperation op5 = mlirOperationCreate(&op5State);
554   MlirOperation op6 = mlirOperationCreate(&op6State);
555   MlirOperation op7 = mlirOperationCreate(&op7State);
556   MlirOperation op8 = mlirOperationCreate(&op8State);
557 
558   // Insert operations in the first block so as to obtain the 1-2-3-4 order.
559   MlirOperation nullOperation = mlirBlockGetFirstOperation(block1);
560   assert(mlirOperationIsNull(nullOperation));
561   mlirBlockInsertOwnedOperationBefore(block1, nullOperation, op3);
562   mlirBlockInsertOwnedOperationBefore(block1, op3, op2);
563   mlirBlockInsertOwnedOperationAfter(block1, nullOperation, op1);
564   mlirBlockInsertOwnedOperationAfter(block1, op3, op4);
565 
566   // Append operations to the rest of blocks to make them non-empty and thus
567   // printable.
568   mlirBlockAppendOwnedOperation(block2, op5);
569   mlirBlockAppendOwnedOperation(block3, op6);
570   mlirBlockAppendOwnedOperation(block4, op7);
571   mlirBlockAppendOwnedOperation(block5, op8);
572 
573   // Remove block5.
574   mlirBlockDetach(block5);
575   mlirBlockDestroy(block5);
576 
577   mlirOperationDump(op);
578   mlirOperationDestroy(op);
579   mlirContextSetAllowUnregisteredDialects(ctx, false);
580   // clang-format off
581   // CHECK-LABEL:  "insertion.order.test"
582   // CHECK:      ^{{.*}}(%{{.*}}: i1
583   // CHECK:        "dummy.op1"
584   // CHECK-NEXT:   "dummy.op2"
585   // CHECK-NEXT:   "dummy.op3"
586   // CHECK-NEXT:   "dummy.op4"
587   // CHECK:      ^{{.*}}(%{{.*}}: i2
588   // CHECK:        "dummy.op5"
589   // CHECK-NOT:  ^{{.*}}(%{{.*}}: i5
590   // CHECK-NOT:    "dummy.op8"
591   // CHECK:      ^{{.*}}(%{{.*}}: i3
592   // CHECK:        "dummy.op6"
593   // CHECK:      ^{{.*}}(%{{.*}}: i4
594   // CHECK:        "dummy.op7"
595   // clang-format on
596 }
597 
598 /// Creates operations with type inference and tests various failure modes.
599 static int createOperationWithTypeInference(MlirContext ctx) {
600   MlirLocation loc = mlirLocationUnknownGet(ctx);
601   MlirAttribute iAttr = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 4);
602 
603   // The shape.const_size op implements result type inference and is only used
604   // for that reason.
605   MlirOperationState state = mlirOperationStateGet(
606       mlirStringRefCreateFromCString("shape.const_size"), loc);
607   MlirNamedAttribute valueAttr = mlirNamedAttributeGet(
608       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), iAttr);
609   mlirOperationStateAddAttributes(&state, 1, &valueAttr);
610   mlirOperationStateEnableResultTypeInference(&state);
611 
612   // Expect result type inference to succeed.
613   MlirOperation op = mlirOperationCreate(&state);
614   if (mlirOperationIsNull(op)) {
615     fprintf(stderr, "ERROR: Result type inference unexpectedly failed");
616     return 1;
617   }
618 
619   // CHECK: RESULT_TYPE_INFERENCE: !shape.size
620   fprintf(stderr, "RESULT_TYPE_INFERENCE: ");
621   mlirTypeDump(mlirValueGetType(mlirOperationGetResult(op, 0)));
622   fprintf(stderr, "\n");
623   mlirOperationDestroy(op);
624   return 0;
625 }
626 
627 /// Dumps instances of all builtin types to check that C API works correctly.
628 /// Additionally, performs simple identity checks that a builtin type
629 /// constructed with C API can be inspected and has the expected type. The
630 /// latter achieves full coverage of C API for builtin types. Returns 0 on
631 /// success and a non-zero error code on failure.
632 static int printBuiltinTypes(MlirContext ctx) {
633   // Integer types.
634   MlirType i32 = mlirIntegerTypeGet(ctx, 32);
635   MlirType si32 = mlirIntegerTypeSignedGet(ctx, 32);
636   MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
637   if (!mlirTypeIsAInteger(i32) || mlirTypeIsAF32(i32))
638     return 1;
639   if (!mlirTypeIsAInteger(si32) || !mlirIntegerTypeIsSigned(si32))
640     return 2;
641   if (!mlirTypeIsAInteger(ui32) || !mlirIntegerTypeIsUnsigned(ui32))
642     return 3;
643   if (mlirTypeEqual(i32, ui32) || mlirTypeEqual(i32, si32))
644     return 4;
645   if (mlirIntegerTypeGetWidth(i32) != mlirIntegerTypeGetWidth(si32))
646     return 5;
647   fprintf(stderr, "@types\n");
648   mlirTypeDump(i32);
649   fprintf(stderr, "\n");
650   mlirTypeDump(si32);
651   fprintf(stderr, "\n");
652   mlirTypeDump(ui32);
653   fprintf(stderr, "\n");
654   // CHECK-LABEL: @types
655   // CHECK: i32
656   // CHECK: si32
657   // CHECK: ui32
658 
659   // Index type.
660   MlirType index = mlirIndexTypeGet(ctx);
661   if (!mlirTypeIsAIndex(index))
662     return 6;
663   mlirTypeDump(index);
664   fprintf(stderr, "\n");
665   // CHECK: index
666 
667   // Floating-point types.
668   MlirType bf16 = mlirBF16TypeGet(ctx);
669   MlirType f16 = mlirF16TypeGet(ctx);
670   MlirType f32 = mlirF32TypeGet(ctx);
671   MlirType f64 = mlirF64TypeGet(ctx);
672   if (!mlirTypeIsABF16(bf16))
673     return 7;
674   if (!mlirTypeIsAF16(f16))
675     return 9;
676   if (!mlirTypeIsAF32(f32))
677     return 10;
678   if (!mlirTypeIsAF64(f64))
679     return 11;
680   mlirTypeDump(bf16);
681   fprintf(stderr, "\n");
682   mlirTypeDump(f16);
683   fprintf(stderr, "\n");
684   mlirTypeDump(f32);
685   fprintf(stderr, "\n");
686   mlirTypeDump(f64);
687   fprintf(stderr, "\n");
688   // CHECK: bf16
689   // CHECK: f16
690   // CHECK: f32
691   // CHECK: f64
692 
693   // None type.
694   MlirType none = mlirNoneTypeGet(ctx);
695   if (!mlirTypeIsANone(none))
696     return 12;
697   mlirTypeDump(none);
698   fprintf(stderr, "\n");
699   // CHECK: none
700 
701   // Complex type.
702   MlirType cplx = mlirComplexTypeGet(f32);
703   if (!mlirTypeIsAComplex(cplx) ||
704       !mlirTypeEqual(mlirComplexTypeGetElementType(cplx), f32))
705     return 13;
706   mlirTypeDump(cplx);
707   fprintf(stderr, "\n");
708   // CHECK: complex<f32>
709 
710   // Vector (and Shaped) type. ShapedType is a common base class for vectors,
711   // memrefs and tensors, one cannot create instances of this class so it is
712   // tested on an instance of vector type.
713   int64_t shape[] = {2, 3};
714   MlirType vector =
715       mlirVectorTypeGet(sizeof(shape) / sizeof(int64_t), shape, f32);
716   if (!mlirTypeIsAVector(vector) || !mlirTypeIsAShaped(vector))
717     return 14;
718   if (!mlirTypeEqual(mlirShapedTypeGetElementType(vector), f32) ||
719       !mlirShapedTypeHasRank(vector) || mlirShapedTypeGetRank(vector) != 2 ||
720       mlirShapedTypeGetDimSize(vector, 0) != 2 ||
721       mlirShapedTypeIsDynamicDim(vector, 0) ||
722       mlirShapedTypeGetDimSize(vector, 1) != 3 ||
723       !mlirShapedTypeHasStaticShape(vector))
724     return 15;
725   mlirTypeDump(vector);
726   fprintf(stderr, "\n");
727   // CHECK: vector<2x3xf32>
728 
729   // Ranked tensor type.
730   MlirType rankedTensor = mlirRankedTensorTypeGet(
731       sizeof(shape) / sizeof(int64_t), shape, f32, mlirAttributeGetNull());
732   if (!mlirTypeIsATensor(rankedTensor) ||
733       !mlirTypeIsARankedTensor(rankedTensor) ||
734       !mlirAttributeIsNull(mlirRankedTensorTypeGetEncoding(rankedTensor)))
735     return 16;
736   mlirTypeDump(rankedTensor);
737   fprintf(stderr, "\n");
738   // CHECK: tensor<2x3xf32>
739 
740   // Unranked tensor type.
741   MlirType unrankedTensor = mlirUnrankedTensorTypeGet(f32);
742   if (!mlirTypeIsATensor(unrankedTensor) ||
743       !mlirTypeIsAUnrankedTensor(unrankedTensor) ||
744       mlirShapedTypeHasRank(unrankedTensor))
745     return 17;
746   mlirTypeDump(unrankedTensor);
747   fprintf(stderr, "\n");
748   // CHECK: tensor<*xf32>
749 
750   // MemRef type.
751   MlirAttribute memSpace2 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 2);
752   MlirType memRef = mlirMemRefTypeContiguousGet(
753       f32, sizeof(shape) / sizeof(int64_t), shape, memSpace2);
754   if (!mlirTypeIsAMemRef(memRef) ||
755       !mlirAttributeEqual(mlirMemRefTypeGetMemorySpace(memRef), memSpace2))
756     return 18;
757   mlirTypeDump(memRef);
758   fprintf(stderr, "\n");
759   // CHECK: memref<2x3xf32, 2>
760 
761   // Unranked MemRef type.
762   MlirAttribute memSpace4 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 4);
763   MlirType unrankedMemRef = mlirUnrankedMemRefTypeGet(f32, memSpace4);
764   if (!mlirTypeIsAUnrankedMemRef(unrankedMemRef) ||
765       mlirTypeIsAMemRef(unrankedMemRef) ||
766       !mlirAttributeEqual(mlirUnrankedMemrefGetMemorySpace(unrankedMemRef),
767                           memSpace4))
768     return 19;
769   mlirTypeDump(unrankedMemRef);
770   fprintf(stderr, "\n");
771   // CHECK: memref<*xf32, 4>
772 
773   // Tuple type.
774   MlirType types[] = {unrankedMemRef, f32};
775   MlirType tuple = mlirTupleTypeGet(ctx, 2, types);
776   if (!mlirTypeIsATuple(tuple) || mlirTupleTypeGetNumTypes(tuple) != 2 ||
777       !mlirTypeEqual(mlirTupleTypeGetType(tuple, 0), unrankedMemRef) ||
778       !mlirTypeEqual(mlirTupleTypeGetType(tuple, 1), f32))
779     return 20;
780   mlirTypeDump(tuple);
781   fprintf(stderr, "\n");
782   // CHECK: tuple<memref<*xf32, 4>, f32>
783 
784   // Function type.
785   MlirType funcInputs[2] = {mlirIndexTypeGet(ctx), mlirIntegerTypeGet(ctx, 1)};
786   MlirType funcResults[3] = {mlirIntegerTypeGet(ctx, 16),
787                              mlirIntegerTypeGet(ctx, 32),
788                              mlirIntegerTypeGet(ctx, 64)};
789   MlirType funcType = mlirFunctionTypeGet(ctx, 2, funcInputs, 3, funcResults);
790   if (mlirFunctionTypeGetNumInputs(funcType) != 2)
791     return 21;
792   if (mlirFunctionTypeGetNumResults(funcType) != 3)
793     return 22;
794   if (!mlirTypeEqual(funcInputs[0], mlirFunctionTypeGetInput(funcType, 0)) ||
795       !mlirTypeEqual(funcInputs[1], mlirFunctionTypeGetInput(funcType, 1)))
796     return 23;
797   if (!mlirTypeEqual(funcResults[0], mlirFunctionTypeGetResult(funcType, 0)) ||
798       !mlirTypeEqual(funcResults[1], mlirFunctionTypeGetResult(funcType, 1)) ||
799       !mlirTypeEqual(funcResults[2], mlirFunctionTypeGetResult(funcType, 2)))
800     return 24;
801   mlirTypeDump(funcType);
802   fprintf(stderr, "\n");
803   // CHECK: (index, i1) -> (i16, i32, i64)
804 
805   // Opaque type.
806   MlirStringRef namespace = mlirStringRefCreate("dialect", 7);
807   MlirStringRef data = mlirStringRefCreate("type", 4);
808   mlirContextSetAllowUnregisteredDialects(ctx, true);
809   MlirType opaque = mlirOpaqueTypeGet(ctx, namespace, data);
810   mlirContextSetAllowUnregisteredDialects(ctx, false);
811   if (!mlirTypeIsAOpaque(opaque) ||
812       !mlirStringRefEqual(mlirOpaqueTypeGetDialectNamespace(opaque),
813                           namespace) ||
814       !mlirStringRefEqual(mlirOpaqueTypeGetData(opaque), data))
815     return 25;
816   mlirTypeDump(opaque);
817   fprintf(stderr, "\n");
818   // CHECK: !dialect.type
819 
820   return 0;
821 }
822 
823 void callbackSetFixedLengthString(const char *data, intptr_t len,
824                                   void *userData) {
825   strncpy(userData, data, len);
826 }
827 
828 bool stringIsEqual(const char *lhs, MlirStringRef rhs) {
829   if (strlen(lhs) != rhs.length) {
830     return false;
831   }
832   return !strncmp(lhs, rhs.data, rhs.length);
833 }
834 
835 int printBuiltinAttributes(MlirContext ctx) {
836   MlirAttribute floating =
837       mlirFloatAttrDoubleGet(ctx, mlirF64TypeGet(ctx), 2.0);
838   if (!mlirAttributeIsAFloat(floating) ||
839       fabs(mlirFloatAttrGetValueDouble(floating) - 2.0) > 1E-6)
840     return 1;
841   fprintf(stderr, "@attrs\n");
842   mlirAttributeDump(floating);
843   // CHECK-LABEL: @attrs
844   // CHECK: 2.000000e+00 : f64
845 
846   // Exercise mlirAttributeGetType() just for the first one.
847   MlirType floatingType = mlirAttributeGetType(floating);
848   mlirTypeDump(floatingType);
849   // CHECK: f64
850 
851   MlirAttribute integer = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 42);
852   MlirAttribute signedInteger =
853       mlirIntegerAttrGet(mlirIntegerTypeSignedGet(ctx, 8), -1);
854   MlirAttribute unsignedInteger =
855       mlirIntegerAttrGet(mlirIntegerTypeUnsignedGet(ctx, 8), 255);
856   if (!mlirAttributeIsAInteger(integer) ||
857       mlirIntegerAttrGetValueInt(integer) != 42 ||
858       mlirIntegerAttrGetValueSInt(signedInteger) != -1 ||
859       mlirIntegerAttrGetValueUInt(unsignedInteger) != 255)
860     return 2;
861   mlirAttributeDump(integer);
862   mlirAttributeDump(signedInteger);
863   mlirAttributeDump(unsignedInteger);
864   // CHECK: 42 : i32
865   // CHECK: -1 : si8
866   // CHECK: 255 : ui8
867 
868   MlirAttribute boolean = mlirBoolAttrGet(ctx, 1);
869   if (!mlirAttributeIsABool(boolean) || !mlirBoolAttrGetValue(boolean))
870     return 3;
871   mlirAttributeDump(boolean);
872   // CHECK: true
873 
874   const char data[] = "abcdefghijklmnopqestuvwxyz";
875   MlirAttribute opaque =
876       mlirOpaqueAttrGet(ctx, mlirStringRefCreateFromCString("func"), 3, data,
877                         mlirNoneTypeGet(ctx));
878   if (!mlirAttributeIsAOpaque(opaque) ||
879       !stringIsEqual("func", mlirOpaqueAttrGetDialectNamespace(opaque)))
880     return 4;
881 
882   MlirStringRef opaqueData = mlirOpaqueAttrGetData(opaque);
883   if (opaqueData.length != 3 ||
884       strncmp(data, opaqueData.data, opaqueData.length))
885     return 5;
886   mlirAttributeDump(opaque);
887   // CHECK: #func.abc
888 
889   MlirAttribute string =
890       mlirStringAttrGet(ctx, mlirStringRefCreate(data + 3, 2));
891   if (!mlirAttributeIsAString(string))
892     return 6;
893 
894   MlirStringRef stringValue = mlirStringAttrGetValue(string);
895   if (stringValue.length != 2 ||
896       strncmp(data + 3, stringValue.data, stringValue.length))
897     return 7;
898   mlirAttributeDump(string);
899   // CHECK: "de"
900 
901   MlirAttribute flatSymbolRef =
902       mlirFlatSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 5, 3));
903   if (!mlirAttributeIsAFlatSymbolRef(flatSymbolRef))
904     return 8;
905 
906   MlirStringRef flatSymbolRefValue =
907       mlirFlatSymbolRefAttrGetValue(flatSymbolRef);
908   if (flatSymbolRefValue.length != 3 ||
909       strncmp(data + 5, flatSymbolRefValue.data, flatSymbolRefValue.length))
910     return 9;
911   mlirAttributeDump(flatSymbolRef);
912   // CHECK: @fgh
913 
914   MlirAttribute symbols[] = {flatSymbolRef, flatSymbolRef};
915   MlirAttribute symbolRef =
916       mlirSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 8, 2), 2, symbols);
917   if (!mlirAttributeIsASymbolRef(symbolRef) ||
918       mlirSymbolRefAttrGetNumNestedReferences(symbolRef) != 2 ||
919       !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 0),
920                           flatSymbolRef) ||
921       !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 1),
922                           flatSymbolRef))
923     return 10;
924 
925   MlirStringRef symbolRefLeaf = mlirSymbolRefAttrGetLeafReference(symbolRef);
926   MlirStringRef symbolRefRoot = mlirSymbolRefAttrGetRootReference(symbolRef);
927   if (symbolRefLeaf.length != 3 ||
928       strncmp(data + 5, symbolRefLeaf.data, symbolRefLeaf.length) ||
929       symbolRefRoot.length != 2 ||
930       strncmp(data + 8, symbolRefRoot.data, symbolRefRoot.length))
931     return 11;
932   mlirAttributeDump(symbolRef);
933   // CHECK: @ij::@fgh::@fgh
934 
935   MlirAttribute type = mlirTypeAttrGet(mlirF32TypeGet(ctx));
936   if (!mlirAttributeIsAType(type) ||
937       !mlirTypeEqual(mlirF32TypeGet(ctx), mlirTypeAttrGetValue(type)))
938     return 12;
939   mlirAttributeDump(type);
940   // CHECK: f32
941 
942   MlirAttribute unit = mlirUnitAttrGet(ctx);
943   if (!mlirAttributeIsAUnit(unit))
944     return 13;
945   mlirAttributeDump(unit);
946   // CHECK: unit
947 
948   int64_t shape[] = {1, 2};
949 
950   int bools[] = {0, 1};
951   uint8_t uints8[] = {0u, 1u};
952   int8_t ints8[] = {0, 1};
953   uint16_t uints16[] = {0u, 1u};
954   int16_t ints16[] = {0, 1};
955   uint32_t uints32[] = {0u, 1u};
956   int32_t ints32[] = {0, 1};
957   uint64_t uints64[] = {0u, 1u};
958   int64_t ints64[] = {0, 1};
959   float floats[] = {0.0f, 1.0f};
960   double doubles[] = {0.0, 1.0};
961   uint16_t bf16s[] = {0x0, 0x3f80};
962   MlirAttribute encoding = mlirAttributeGetNull();
963   MlirAttribute boolElements = mlirDenseElementsAttrBoolGet(
964       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
965       2, bools);
966   MlirAttribute uint8Elements = mlirDenseElementsAttrUInt8Get(
967       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
968                               encoding),
969       2, uints8);
970   MlirAttribute int8Elements = mlirDenseElementsAttrInt8Get(
971       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
972       2, ints8);
973   MlirAttribute uint16Elements = mlirDenseElementsAttrUInt16Get(
974       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 16),
975                               encoding),
976       2, uints16);
977   MlirAttribute int16Elements = mlirDenseElementsAttrInt16Get(
978       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 16), encoding),
979       2, ints16);
980   MlirAttribute uint32Elements = mlirDenseElementsAttrUInt32Get(
981       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
982                               encoding),
983       2, uints32);
984   MlirAttribute int32Elements = mlirDenseElementsAttrInt32Get(
985       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
986       2, ints32);
987   MlirAttribute uint64Elements = mlirDenseElementsAttrUInt64Get(
988       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
989                               encoding),
990       2, uints64);
991   MlirAttribute int64Elements = mlirDenseElementsAttrInt64Get(
992       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
993       2, ints64);
994   MlirAttribute floatElements = mlirDenseElementsAttrFloatGet(
995       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 2,
996       floats);
997   MlirAttribute doubleElements = mlirDenseElementsAttrDoubleGet(
998       mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 2,
999       doubles);
1000   MlirAttribute bf16Elements = mlirDenseElementsAttrBFloat16Get(
1001       mlirRankedTensorTypeGet(2, shape, mlirBF16TypeGet(ctx), encoding), 2,
1002       bf16s);
1003 
1004   if (!mlirAttributeIsADenseElements(boolElements) ||
1005       !mlirAttributeIsADenseElements(uint8Elements) ||
1006       !mlirAttributeIsADenseElements(int8Elements) ||
1007       !mlirAttributeIsADenseElements(uint32Elements) ||
1008       !mlirAttributeIsADenseElements(int32Elements) ||
1009       !mlirAttributeIsADenseElements(uint64Elements) ||
1010       !mlirAttributeIsADenseElements(int64Elements) ||
1011       !mlirAttributeIsADenseElements(floatElements) ||
1012       !mlirAttributeIsADenseElements(doubleElements) ||
1013       !mlirAttributeIsADenseElements(bf16Elements))
1014     return 14;
1015 
1016   if (mlirDenseElementsAttrGetBoolValue(boolElements, 1) != 1 ||
1017       mlirDenseElementsAttrGetUInt8Value(uint8Elements, 1) != 1 ||
1018       mlirDenseElementsAttrGetInt8Value(int8Elements, 1) != 1 ||
1019       mlirDenseElementsAttrGetUInt16Value(uint16Elements, 1) != 1 ||
1020       mlirDenseElementsAttrGetInt16Value(int16Elements, 1) != 1 ||
1021       mlirDenseElementsAttrGetUInt32Value(uint32Elements, 1) != 1 ||
1022       mlirDenseElementsAttrGetInt32Value(int32Elements, 1) != 1 ||
1023       mlirDenseElementsAttrGetUInt64Value(uint64Elements, 1) != 1 ||
1024       mlirDenseElementsAttrGetInt64Value(int64Elements, 1) != 1 ||
1025       fabsf(mlirDenseElementsAttrGetFloatValue(floatElements, 1) - 1.0f) >
1026           1E-6f ||
1027       fabs(mlirDenseElementsAttrGetDoubleValue(doubleElements, 1) - 1.0) > 1E-6)
1028     return 15;
1029 
1030   mlirAttributeDump(boolElements);
1031   mlirAttributeDump(uint8Elements);
1032   mlirAttributeDump(int8Elements);
1033   mlirAttributeDump(uint32Elements);
1034   mlirAttributeDump(int32Elements);
1035   mlirAttributeDump(uint64Elements);
1036   mlirAttributeDump(int64Elements);
1037   mlirAttributeDump(floatElements);
1038   mlirAttributeDump(doubleElements);
1039   mlirAttributeDump(bf16Elements);
1040   // CHECK: dense<{{\[}}[false, true]]> : tensor<1x2xi1>
1041   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui8>
1042   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi8>
1043   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui32>
1044   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi32>
1045   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui64>
1046   // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi64>
1047   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf32>
1048   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf64>
1049   // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xbf16>
1050 
1051   MlirAttribute splatBool = mlirDenseElementsAttrBoolSplatGet(
1052       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
1053       1);
1054   MlirAttribute splatUInt8 = mlirDenseElementsAttrUInt8SplatGet(
1055       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
1056                               encoding),
1057       1);
1058   MlirAttribute splatInt8 = mlirDenseElementsAttrInt8SplatGet(
1059       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
1060       1);
1061   MlirAttribute splatUInt32 = mlirDenseElementsAttrUInt32SplatGet(
1062       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
1063                               encoding),
1064       1);
1065   MlirAttribute splatInt32 = mlirDenseElementsAttrInt32SplatGet(
1066       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
1067       1);
1068   MlirAttribute splatUInt64 = mlirDenseElementsAttrUInt64SplatGet(
1069       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
1070                               encoding),
1071       1);
1072   MlirAttribute splatInt64 = mlirDenseElementsAttrInt64SplatGet(
1073       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
1074       1);
1075   MlirAttribute splatFloat = mlirDenseElementsAttrFloatSplatGet(
1076       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 1.0f);
1077   MlirAttribute splatDouble = mlirDenseElementsAttrDoubleSplatGet(
1078       mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 1.0);
1079 
1080   if (!mlirAttributeIsADenseElements(splatBool) ||
1081       !mlirDenseElementsAttrIsSplat(splatBool) ||
1082       !mlirAttributeIsADenseElements(splatUInt8) ||
1083       !mlirDenseElementsAttrIsSplat(splatUInt8) ||
1084       !mlirAttributeIsADenseElements(splatInt8) ||
1085       !mlirDenseElementsAttrIsSplat(splatInt8) ||
1086       !mlirAttributeIsADenseElements(splatUInt32) ||
1087       !mlirDenseElementsAttrIsSplat(splatUInt32) ||
1088       !mlirAttributeIsADenseElements(splatInt32) ||
1089       !mlirDenseElementsAttrIsSplat(splatInt32) ||
1090       !mlirAttributeIsADenseElements(splatUInt64) ||
1091       !mlirDenseElementsAttrIsSplat(splatUInt64) ||
1092       !mlirAttributeIsADenseElements(splatInt64) ||
1093       !mlirDenseElementsAttrIsSplat(splatInt64) ||
1094       !mlirAttributeIsADenseElements(splatFloat) ||
1095       !mlirDenseElementsAttrIsSplat(splatFloat) ||
1096       !mlirAttributeIsADenseElements(splatDouble) ||
1097       !mlirDenseElementsAttrIsSplat(splatDouble))
1098     return 16;
1099 
1100   if (mlirDenseElementsAttrGetBoolSplatValue(splatBool) != 1 ||
1101       mlirDenseElementsAttrGetUInt8SplatValue(splatUInt8) != 1 ||
1102       mlirDenseElementsAttrGetInt8SplatValue(splatInt8) != 1 ||
1103       mlirDenseElementsAttrGetUInt32SplatValue(splatUInt32) != 1 ||
1104       mlirDenseElementsAttrGetInt32SplatValue(splatInt32) != 1 ||
1105       mlirDenseElementsAttrGetUInt64SplatValue(splatUInt64) != 1 ||
1106       mlirDenseElementsAttrGetInt64SplatValue(splatInt64) != 1 ||
1107       fabsf(mlirDenseElementsAttrGetFloatSplatValue(splatFloat) - 1.0f) >
1108           1E-6f ||
1109       fabs(mlirDenseElementsAttrGetDoubleSplatValue(splatDouble) - 1.0) > 1E-6)
1110     return 17;
1111 
1112   uint8_t *uint8RawData =
1113       (uint8_t *)mlirDenseElementsAttrGetRawData(uint8Elements);
1114   int8_t *int8RawData = (int8_t *)mlirDenseElementsAttrGetRawData(int8Elements);
1115   uint32_t *uint32RawData =
1116       (uint32_t *)mlirDenseElementsAttrGetRawData(uint32Elements);
1117   int32_t *int32RawData =
1118       (int32_t *)mlirDenseElementsAttrGetRawData(int32Elements);
1119   uint64_t *uint64RawData =
1120       (uint64_t *)mlirDenseElementsAttrGetRawData(uint64Elements);
1121   int64_t *int64RawData =
1122       (int64_t *)mlirDenseElementsAttrGetRawData(int64Elements);
1123   float *floatRawData = (float *)mlirDenseElementsAttrGetRawData(floatElements);
1124   double *doubleRawData =
1125       (double *)mlirDenseElementsAttrGetRawData(doubleElements);
1126   uint16_t *bf16RawData =
1127       (uint16_t *)mlirDenseElementsAttrGetRawData(bf16Elements);
1128   if (uint8RawData[0] != 0u || uint8RawData[1] != 1u || int8RawData[0] != 0 ||
1129       int8RawData[1] != 1 || uint32RawData[0] != 0u || uint32RawData[1] != 1u ||
1130       int32RawData[0] != 0 || int32RawData[1] != 1 || uint64RawData[0] != 0u ||
1131       uint64RawData[1] != 1u || int64RawData[0] != 0 || int64RawData[1] != 1 ||
1132       floatRawData[0] != 0.0f || floatRawData[1] != 1.0f ||
1133       doubleRawData[0] != 0.0 || doubleRawData[1] != 1.0 ||
1134       bf16RawData[0] != 0 || bf16RawData[1] != 0x3f80)
1135     return 18;
1136 
1137   mlirAttributeDump(splatBool);
1138   mlirAttributeDump(splatUInt8);
1139   mlirAttributeDump(splatInt8);
1140   mlirAttributeDump(splatUInt32);
1141   mlirAttributeDump(splatInt32);
1142   mlirAttributeDump(splatUInt64);
1143   mlirAttributeDump(splatInt64);
1144   mlirAttributeDump(splatFloat);
1145   mlirAttributeDump(splatDouble);
1146   // CHECK: dense<true> : tensor<1x2xi1>
1147   // CHECK: dense<1> : tensor<1x2xui8>
1148   // CHECK: dense<1> : tensor<1x2xi8>
1149   // CHECK: dense<1> : tensor<1x2xui32>
1150   // CHECK: dense<1> : tensor<1x2xi32>
1151   // CHECK: dense<1> : tensor<1x2xui64>
1152   // CHECK: dense<1> : tensor<1x2xi64>
1153   // CHECK: dense<1.000000e+00> : tensor<1x2xf32>
1154   // CHECK: dense<1.000000e+00> : tensor<1x2xf64>
1155 
1156   mlirAttributeDump(mlirElementsAttrGetValue(floatElements, 2, uints64));
1157   mlirAttributeDump(mlirElementsAttrGetValue(doubleElements, 2, uints64));
1158   mlirAttributeDump(mlirElementsAttrGetValue(bf16Elements, 2, uints64));
1159   // CHECK: 1.000000e+00 : f32
1160   // CHECK: 1.000000e+00 : f64
1161   // CHECK: 1.000000e+00 : bf16
1162 
1163   int64_t indices[] = {0, 1};
1164   int64_t one = 1;
1165   MlirAttribute indicesAttr = mlirDenseElementsAttrInt64Get(
1166       mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
1167       2, indices);
1168   MlirAttribute valuesAttr = mlirDenseElementsAttrFloatGet(
1169       mlirRankedTensorTypeGet(1, &one, mlirF32TypeGet(ctx), encoding), 1,
1170       floats);
1171   MlirAttribute sparseAttr = mlirSparseElementsAttribute(
1172       mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding),
1173       indicesAttr, valuesAttr);
1174   mlirAttributeDump(sparseAttr);
1175   // CHECK: sparse<{{\[}}[0, 1]], 0.000000e+00> : tensor<1x2xf32>
1176 
1177   return 0;
1178 }
1179 
1180 int printAffineMap(MlirContext ctx) {
1181   MlirAffineMap emptyAffineMap = mlirAffineMapEmptyGet(ctx);
1182   MlirAffineMap affineMap = mlirAffineMapZeroResultGet(ctx, 3, 2);
1183   MlirAffineMap constAffineMap = mlirAffineMapConstantGet(ctx, 2);
1184   MlirAffineMap multiDimIdentityAffineMap =
1185       mlirAffineMapMultiDimIdentityGet(ctx, 3);
1186   MlirAffineMap minorIdentityAffineMap =
1187       mlirAffineMapMinorIdentityGet(ctx, 3, 2);
1188   unsigned permutation[] = {1, 2, 0};
1189   MlirAffineMap permutationAffineMap = mlirAffineMapPermutationGet(
1190       ctx, sizeof(permutation) / sizeof(unsigned), permutation);
1191 
1192   fprintf(stderr, "@affineMap\n");
1193   mlirAffineMapDump(emptyAffineMap);
1194   mlirAffineMapDump(affineMap);
1195   mlirAffineMapDump(constAffineMap);
1196   mlirAffineMapDump(multiDimIdentityAffineMap);
1197   mlirAffineMapDump(minorIdentityAffineMap);
1198   mlirAffineMapDump(permutationAffineMap);
1199   // CHECK-LABEL: @affineMap
1200   // CHECK: () -> ()
1201   // CHECK: (d0, d1, d2)[s0, s1] -> ()
1202   // CHECK: () -> (2)
1203   // CHECK: (d0, d1, d2) -> (d0, d1, d2)
1204   // CHECK: (d0, d1, d2) -> (d1, d2)
1205   // CHECK: (d0, d1, d2) -> (d1, d2, d0)
1206 
1207   if (!mlirAffineMapIsIdentity(emptyAffineMap) ||
1208       mlirAffineMapIsIdentity(affineMap) ||
1209       mlirAffineMapIsIdentity(constAffineMap) ||
1210       !mlirAffineMapIsIdentity(multiDimIdentityAffineMap) ||
1211       mlirAffineMapIsIdentity(minorIdentityAffineMap) ||
1212       mlirAffineMapIsIdentity(permutationAffineMap))
1213     return 1;
1214 
1215   if (!mlirAffineMapIsMinorIdentity(emptyAffineMap) ||
1216       mlirAffineMapIsMinorIdentity(affineMap) ||
1217       !mlirAffineMapIsMinorIdentity(multiDimIdentityAffineMap) ||
1218       !mlirAffineMapIsMinorIdentity(minorIdentityAffineMap) ||
1219       mlirAffineMapIsMinorIdentity(permutationAffineMap))
1220     return 2;
1221 
1222   if (!mlirAffineMapIsEmpty(emptyAffineMap) ||
1223       mlirAffineMapIsEmpty(affineMap) || mlirAffineMapIsEmpty(constAffineMap) ||
1224       mlirAffineMapIsEmpty(multiDimIdentityAffineMap) ||
1225       mlirAffineMapIsEmpty(minorIdentityAffineMap) ||
1226       mlirAffineMapIsEmpty(permutationAffineMap))
1227     return 3;
1228 
1229   if (mlirAffineMapIsSingleConstant(emptyAffineMap) ||
1230       mlirAffineMapIsSingleConstant(affineMap) ||
1231       !mlirAffineMapIsSingleConstant(constAffineMap) ||
1232       mlirAffineMapIsSingleConstant(multiDimIdentityAffineMap) ||
1233       mlirAffineMapIsSingleConstant(minorIdentityAffineMap) ||
1234       mlirAffineMapIsSingleConstant(permutationAffineMap))
1235     return 4;
1236 
1237   if (mlirAffineMapGetSingleConstantResult(constAffineMap) != 2)
1238     return 5;
1239 
1240   if (mlirAffineMapGetNumDims(emptyAffineMap) != 0 ||
1241       mlirAffineMapGetNumDims(affineMap) != 3 ||
1242       mlirAffineMapGetNumDims(constAffineMap) != 0 ||
1243       mlirAffineMapGetNumDims(multiDimIdentityAffineMap) != 3 ||
1244       mlirAffineMapGetNumDims(minorIdentityAffineMap) != 3 ||
1245       mlirAffineMapGetNumDims(permutationAffineMap) != 3)
1246     return 6;
1247 
1248   if (mlirAffineMapGetNumSymbols(emptyAffineMap) != 0 ||
1249       mlirAffineMapGetNumSymbols(affineMap) != 2 ||
1250       mlirAffineMapGetNumSymbols(constAffineMap) != 0 ||
1251       mlirAffineMapGetNumSymbols(multiDimIdentityAffineMap) != 0 ||
1252       mlirAffineMapGetNumSymbols(minorIdentityAffineMap) != 0 ||
1253       mlirAffineMapGetNumSymbols(permutationAffineMap) != 0)
1254     return 7;
1255 
1256   if (mlirAffineMapGetNumResults(emptyAffineMap) != 0 ||
1257       mlirAffineMapGetNumResults(affineMap) != 0 ||
1258       mlirAffineMapGetNumResults(constAffineMap) != 1 ||
1259       mlirAffineMapGetNumResults(multiDimIdentityAffineMap) != 3 ||
1260       mlirAffineMapGetNumResults(minorIdentityAffineMap) != 2 ||
1261       mlirAffineMapGetNumResults(permutationAffineMap) != 3)
1262     return 8;
1263 
1264   if (mlirAffineMapGetNumInputs(emptyAffineMap) != 0 ||
1265       mlirAffineMapGetNumInputs(affineMap) != 5 ||
1266       mlirAffineMapGetNumInputs(constAffineMap) != 0 ||
1267       mlirAffineMapGetNumInputs(multiDimIdentityAffineMap) != 3 ||
1268       mlirAffineMapGetNumInputs(minorIdentityAffineMap) != 3 ||
1269       mlirAffineMapGetNumInputs(permutationAffineMap) != 3)
1270     return 9;
1271 
1272   if (!mlirAffineMapIsProjectedPermutation(emptyAffineMap) ||
1273       !mlirAffineMapIsPermutation(emptyAffineMap) ||
1274       mlirAffineMapIsProjectedPermutation(affineMap) ||
1275       mlirAffineMapIsPermutation(affineMap) ||
1276       mlirAffineMapIsProjectedPermutation(constAffineMap) ||
1277       mlirAffineMapIsPermutation(constAffineMap) ||
1278       !mlirAffineMapIsProjectedPermutation(multiDimIdentityAffineMap) ||
1279       !mlirAffineMapIsPermutation(multiDimIdentityAffineMap) ||
1280       !mlirAffineMapIsProjectedPermutation(minorIdentityAffineMap) ||
1281       mlirAffineMapIsPermutation(minorIdentityAffineMap) ||
1282       !mlirAffineMapIsProjectedPermutation(permutationAffineMap) ||
1283       !mlirAffineMapIsPermutation(permutationAffineMap))
1284     return 10;
1285 
1286   intptr_t sub[] = {1};
1287 
1288   MlirAffineMap subMap = mlirAffineMapGetSubMap(
1289       multiDimIdentityAffineMap, sizeof(sub) / sizeof(intptr_t), sub);
1290   MlirAffineMap majorSubMap =
1291       mlirAffineMapGetMajorSubMap(multiDimIdentityAffineMap, 1);
1292   MlirAffineMap minorSubMap =
1293       mlirAffineMapGetMinorSubMap(multiDimIdentityAffineMap, 1);
1294 
1295   mlirAffineMapDump(subMap);
1296   mlirAffineMapDump(majorSubMap);
1297   mlirAffineMapDump(minorSubMap);
1298   // CHECK: (d0, d1, d2) -> (d1)
1299   // CHECK: (d0, d1, d2) -> (d0)
1300   // CHECK: (d0, d1, d2) -> (d2)
1301 
1302   return 0;
1303 }
1304 
1305 int printAffineExpr(MlirContext ctx) {
1306   MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 5);
1307   MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 5);
1308   MlirAffineExpr affineConstantExpr = mlirAffineConstantExprGet(ctx, 5);
1309   MlirAffineExpr affineAddExpr =
1310       mlirAffineAddExprGet(affineDimExpr, affineSymbolExpr);
1311   MlirAffineExpr affineMulExpr =
1312       mlirAffineMulExprGet(affineDimExpr, affineSymbolExpr);
1313   MlirAffineExpr affineModExpr =
1314       mlirAffineModExprGet(affineDimExpr, affineSymbolExpr);
1315   MlirAffineExpr affineFloorDivExpr =
1316       mlirAffineFloorDivExprGet(affineDimExpr, affineSymbolExpr);
1317   MlirAffineExpr affineCeilDivExpr =
1318       mlirAffineCeilDivExprGet(affineDimExpr, affineSymbolExpr);
1319 
1320   // Tests mlirAffineExprDump.
1321   fprintf(stderr, "@affineExpr\n");
1322   mlirAffineExprDump(affineDimExpr);
1323   mlirAffineExprDump(affineSymbolExpr);
1324   mlirAffineExprDump(affineConstantExpr);
1325   mlirAffineExprDump(affineAddExpr);
1326   mlirAffineExprDump(affineMulExpr);
1327   mlirAffineExprDump(affineModExpr);
1328   mlirAffineExprDump(affineFloorDivExpr);
1329   mlirAffineExprDump(affineCeilDivExpr);
1330   // CHECK-LABEL: @affineExpr
1331   // CHECK: d5
1332   // CHECK: s5
1333   // CHECK: 5
1334   // CHECK: d5 + s5
1335   // CHECK: d5 * s5
1336   // CHECK: d5 mod s5
1337   // CHECK: d5 floordiv s5
1338   // CHECK: d5 ceildiv s5
1339 
1340   // Tests methods of affine binary operation expression, takes add expression
1341   // as an example.
1342   mlirAffineExprDump(mlirAffineBinaryOpExprGetLHS(affineAddExpr));
1343   mlirAffineExprDump(mlirAffineBinaryOpExprGetRHS(affineAddExpr));
1344   // CHECK: d5
1345   // CHECK: s5
1346 
1347   // Tests methods of affine dimension expression.
1348   if (mlirAffineDimExprGetPosition(affineDimExpr) != 5)
1349     return 1;
1350 
1351   // Tests methods of affine symbol expression.
1352   if (mlirAffineSymbolExprGetPosition(affineSymbolExpr) != 5)
1353     return 2;
1354 
1355   // Tests methods of affine constant expression.
1356   if (mlirAffineConstantExprGetValue(affineConstantExpr) != 5)
1357     return 3;
1358 
1359   // Tests methods of affine expression.
1360   if (mlirAffineExprIsSymbolicOrConstant(affineDimExpr) ||
1361       !mlirAffineExprIsSymbolicOrConstant(affineSymbolExpr) ||
1362       !mlirAffineExprIsSymbolicOrConstant(affineConstantExpr) ||
1363       mlirAffineExprIsSymbolicOrConstant(affineAddExpr) ||
1364       mlirAffineExprIsSymbolicOrConstant(affineMulExpr) ||
1365       mlirAffineExprIsSymbolicOrConstant(affineModExpr) ||
1366       mlirAffineExprIsSymbolicOrConstant(affineFloorDivExpr) ||
1367       mlirAffineExprIsSymbolicOrConstant(affineCeilDivExpr))
1368     return 4;
1369 
1370   if (!mlirAffineExprIsPureAffine(affineDimExpr) ||
1371       !mlirAffineExprIsPureAffine(affineSymbolExpr) ||
1372       !mlirAffineExprIsPureAffine(affineConstantExpr) ||
1373       !mlirAffineExprIsPureAffine(affineAddExpr) ||
1374       mlirAffineExprIsPureAffine(affineMulExpr) ||
1375       mlirAffineExprIsPureAffine(affineModExpr) ||
1376       mlirAffineExprIsPureAffine(affineFloorDivExpr) ||
1377       mlirAffineExprIsPureAffine(affineCeilDivExpr))
1378     return 5;
1379 
1380   if (mlirAffineExprGetLargestKnownDivisor(affineDimExpr) != 1 ||
1381       mlirAffineExprGetLargestKnownDivisor(affineSymbolExpr) != 1 ||
1382       mlirAffineExprGetLargestKnownDivisor(affineConstantExpr) != 5 ||
1383       mlirAffineExprGetLargestKnownDivisor(affineAddExpr) != 1 ||
1384       mlirAffineExprGetLargestKnownDivisor(affineMulExpr) != 1 ||
1385       mlirAffineExprGetLargestKnownDivisor(affineModExpr) != 1 ||
1386       mlirAffineExprGetLargestKnownDivisor(affineFloorDivExpr) != 1 ||
1387       mlirAffineExprGetLargestKnownDivisor(affineCeilDivExpr) != 1)
1388     return 6;
1389 
1390   if (!mlirAffineExprIsMultipleOf(affineDimExpr, 1) ||
1391       !mlirAffineExprIsMultipleOf(affineSymbolExpr, 1) ||
1392       !mlirAffineExprIsMultipleOf(affineConstantExpr, 5) ||
1393       !mlirAffineExprIsMultipleOf(affineAddExpr, 1) ||
1394       !mlirAffineExprIsMultipleOf(affineMulExpr, 1) ||
1395       !mlirAffineExprIsMultipleOf(affineModExpr, 1) ||
1396       !mlirAffineExprIsMultipleOf(affineFloorDivExpr, 1) ||
1397       !mlirAffineExprIsMultipleOf(affineCeilDivExpr, 1))
1398     return 7;
1399 
1400   if (!mlirAffineExprIsFunctionOfDim(affineDimExpr, 5) ||
1401       mlirAffineExprIsFunctionOfDim(affineSymbolExpr, 5) ||
1402       mlirAffineExprIsFunctionOfDim(affineConstantExpr, 5) ||
1403       !mlirAffineExprIsFunctionOfDim(affineAddExpr, 5) ||
1404       !mlirAffineExprIsFunctionOfDim(affineMulExpr, 5) ||
1405       !mlirAffineExprIsFunctionOfDim(affineModExpr, 5) ||
1406       !mlirAffineExprIsFunctionOfDim(affineFloorDivExpr, 5) ||
1407       !mlirAffineExprIsFunctionOfDim(affineCeilDivExpr, 5))
1408     return 8;
1409 
1410   // Tests 'IsA' methods of affine binary operation expression.
1411   if (!mlirAffineExprIsAAdd(affineAddExpr))
1412     return 9;
1413 
1414   if (!mlirAffineExprIsAMul(affineMulExpr))
1415     return 10;
1416 
1417   if (!mlirAffineExprIsAMod(affineModExpr))
1418     return 11;
1419 
1420   if (!mlirAffineExprIsAFloorDiv(affineFloorDivExpr))
1421     return 12;
1422 
1423   if (!mlirAffineExprIsACeilDiv(affineCeilDivExpr))
1424     return 13;
1425 
1426   if (!mlirAffineExprIsABinary(affineAddExpr))
1427     return 14;
1428 
1429   // Test other 'IsA' method on affine expressions.
1430   if (!mlirAffineExprIsAConstant(affineConstantExpr))
1431     return 15;
1432 
1433   if (!mlirAffineExprIsADim(affineDimExpr))
1434     return 16;
1435 
1436   if (!mlirAffineExprIsASymbol(affineSymbolExpr))
1437     return 17;
1438 
1439   // Test equality and nullity.
1440   MlirAffineExpr otherDimExpr = mlirAffineDimExprGet(ctx, 5);
1441   if (!mlirAffineExprEqual(affineDimExpr, otherDimExpr))
1442     return 18;
1443 
1444   if (mlirAffineExprIsNull(affineDimExpr))
1445     return 19;
1446 
1447   return 0;
1448 }
1449 
1450 int affineMapFromExprs(MlirContext ctx) {
1451   MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 0);
1452   MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 1);
1453   MlirAffineExpr exprs[] = {affineDimExpr, affineSymbolExpr};
1454   MlirAffineMap map = mlirAffineMapGet(ctx, 3, 3, 2, exprs);
1455 
1456   // CHECK-LABEL: @affineMapFromExprs
1457   fprintf(stderr, "@affineMapFromExprs");
1458   // CHECK: (d0, d1, d2)[s0, s1, s2] -> (d0, s1)
1459   mlirAffineMapDump(map);
1460 
1461   if (mlirAffineMapGetNumResults(map) != 2)
1462     return 1;
1463 
1464   if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 0), affineDimExpr))
1465     return 2;
1466 
1467   if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 1), affineSymbolExpr))
1468     return 3;
1469 
1470   MlirAffineExpr affineDim2Expr = mlirAffineDimExprGet(ctx, 1);
1471   MlirAffineExpr composed = mlirAffineExprCompose(affineDim2Expr, map);
1472   // CHECK: s1
1473   mlirAffineExprDump(composed);
1474   if (!mlirAffineExprEqual(composed, affineSymbolExpr))
1475     return 4;
1476 
1477   return 0;
1478 }
1479 
1480 int printIntegerSet(MlirContext ctx) {
1481   MlirIntegerSet emptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);
1482 
1483   // CHECK-LABEL: @printIntegerSet
1484   fprintf(stderr, "@printIntegerSet");
1485 
1486   // CHECK: (d0, d1)[s0] : (1 == 0)
1487   mlirIntegerSetDump(emptySet);
1488 
1489   if (!mlirIntegerSetIsCanonicalEmpty(emptySet))
1490     return 1;
1491 
1492   MlirIntegerSet anotherEmptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);
1493   if (!mlirIntegerSetEqual(emptySet, anotherEmptySet))
1494     return 2;
1495 
1496   // Construct a set constrained by:
1497   //   d0 - s0 == 0,
1498   //   d1 - 42 >= 0.
1499   MlirAffineExpr negOne = mlirAffineConstantExprGet(ctx, -1);
1500   MlirAffineExpr negFortyTwo = mlirAffineConstantExprGet(ctx, -42);
1501   MlirAffineExpr d0 = mlirAffineDimExprGet(ctx, 0);
1502   MlirAffineExpr d1 = mlirAffineDimExprGet(ctx, 1);
1503   MlirAffineExpr s0 = mlirAffineSymbolExprGet(ctx, 0);
1504   MlirAffineExpr negS0 = mlirAffineMulExprGet(negOne, s0);
1505   MlirAffineExpr d0minusS0 = mlirAffineAddExprGet(d0, negS0);
1506   MlirAffineExpr d1minus42 = mlirAffineAddExprGet(d1, negFortyTwo);
1507   MlirAffineExpr constraints[] = {d0minusS0, d1minus42};
1508   bool flags[] = {true, false};
1509 
1510   MlirIntegerSet set = mlirIntegerSetGet(ctx, 2, 1, 2, constraints, flags);
1511   // CHECK: (d0, d1)[s0] : (
1512   // CHECK-DAG: d0 - s0 == 0
1513   // CHECK-DAG: d1 - 42 >= 0
1514   mlirIntegerSetDump(set);
1515 
1516   // Transform d1 into s0.
1517   MlirAffineExpr s1 = mlirAffineSymbolExprGet(ctx, 1);
1518   MlirAffineExpr repl[] = {d0, s1};
1519   MlirIntegerSet replaced = mlirIntegerSetReplaceGet(set, repl, &s0, 1, 2);
1520   // CHECK: (d0)[s0, s1] : (
1521   // CHECK-DAG: d0 - s0 == 0
1522   // CHECK-DAG: s1 - 42 >= 0
1523   mlirIntegerSetDump(replaced);
1524 
1525   if (mlirIntegerSetGetNumDims(set) != 2)
1526     return 3;
1527   if (mlirIntegerSetGetNumDims(replaced) != 1)
1528     return 4;
1529 
1530   if (mlirIntegerSetGetNumSymbols(set) != 1)
1531     return 5;
1532   if (mlirIntegerSetGetNumSymbols(replaced) != 2)
1533     return 6;
1534 
1535   if (mlirIntegerSetGetNumInputs(set) != 3)
1536     return 7;
1537 
1538   if (mlirIntegerSetGetNumConstraints(set) != 2)
1539     return 8;
1540 
1541   if (mlirIntegerSetGetNumEqualities(set) != 1)
1542     return 9;
1543 
1544   if (mlirIntegerSetGetNumInequalities(set) != 1)
1545     return 10;
1546 
1547   MlirAffineExpr cstr1 = mlirIntegerSetGetConstraint(set, 0);
1548   MlirAffineExpr cstr2 = mlirIntegerSetGetConstraint(set, 1);
1549   bool isEq1 = mlirIntegerSetIsConstraintEq(set, 0);
1550   bool isEq2 = mlirIntegerSetIsConstraintEq(set, 1);
1551   if (!mlirAffineExprEqual(cstr1, isEq1 ? d0minusS0 : d1minus42))
1552     return 11;
1553   if (!mlirAffineExprEqual(cstr2, isEq2 ? d0minusS0 : d1minus42))
1554     return 12;
1555 
1556   return 0;
1557 }
1558 
1559 int registerOnlyStd() {
1560   MlirContext ctx = mlirContextCreate();
1561   // The built-in dialect is always loaded.
1562   if (mlirContextGetNumLoadedDialects(ctx) != 1)
1563     return 1;
1564 
1565   MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();
1566 
1567   MlirDialect std = mlirContextGetOrLoadDialect(
1568       ctx, mlirDialectHandleGetNamespace(stdHandle));
1569   if (!mlirDialectIsNull(std))
1570     return 2;
1571 
1572   mlirDialectHandleRegisterDialect(stdHandle, ctx);
1573 
1574   std = mlirContextGetOrLoadDialect(ctx,
1575                                     mlirDialectHandleGetNamespace(stdHandle));
1576   if (mlirDialectIsNull(std))
1577     return 3;
1578 
1579   MlirDialect alsoStd = mlirDialectHandleLoadDialect(stdHandle, ctx);
1580   if (!mlirDialectEqual(std, alsoStd))
1581     return 4;
1582 
1583   MlirStringRef stdNs = mlirDialectGetNamespace(std);
1584   MlirStringRef alsoStdNs = mlirDialectHandleGetNamespace(stdHandle);
1585   if (stdNs.length != alsoStdNs.length ||
1586       strncmp(stdNs.data, alsoStdNs.data, stdNs.length))
1587     return 5;
1588 
1589   fprintf(stderr, "@registration\n");
1590   // CHECK-LABEL: @registration
1591 
1592   // CHECK: cf.cond_br is_registered: 1
1593   fprintf(stderr, "cf.cond_br is_registered: %d\n",
1594           mlirContextIsRegisteredOperation(
1595               ctx, mlirStringRefCreateFromCString("cf.cond_br")));
1596 
1597   // CHECK: func.not_existing_op is_registered: 0
1598   fprintf(stderr, "func.not_existing_op is_registered: %d\n",
1599           mlirContextIsRegisteredOperation(
1600               ctx, mlirStringRefCreateFromCString("func.not_existing_op")));
1601 
1602   // CHECK: not_existing_dialect.not_existing_op is_registered: 0
1603   fprintf(stderr, "not_existing_dialect.not_existing_op is_registered: %d\n",
1604           mlirContextIsRegisteredOperation(
1605               ctx, mlirStringRefCreateFromCString(
1606                        "not_existing_dialect.not_existing_op")));
1607 
1608   mlirContextDestroy(ctx);
1609   return 0;
1610 }
1611 
1612 /// Tests backreference APIs
1613 static int testBackreferences() {
1614   fprintf(stderr, "@test_backreferences\n");
1615 
1616   MlirContext ctx = mlirContextCreate();
1617   mlirContextSetAllowUnregisteredDialects(ctx, true);
1618   MlirLocation loc = mlirLocationUnknownGet(ctx);
1619 
1620   MlirOperationState opState =
1621       mlirOperationStateGet(mlirStringRefCreateFromCString("invalid.op"), loc);
1622   MlirRegion region = mlirRegionCreate();
1623   MlirBlock block = mlirBlockCreate(0, NULL, NULL);
1624   mlirRegionAppendOwnedBlock(region, block);
1625   mlirOperationStateAddOwnedRegions(&opState, 1, &region);
1626   MlirOperation op = mlirOperationCreate(&opState);
1627   MlirIdentifier ident =
1628       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("identifier"));
1629 
1630   if (!mlirContextEqual(ctx, mlirOperationGetContext(op))) {
1631     fprintf(stderr, "ERROR: Getting context from operation failed\n");
1632     return 1;
1633   }
1634   if (!mlirOperationEqual(op, mlirBlockGetParentOperation(block))) {
1635     fprintf(stderr, "ERROR: Getting parent operation from block failed\n");
1636     return 2;
1637   }
1638   if (!mlirContextEqual(ctx, mlirIdentifierGetContext(ident))) {
1639     fprintf(stderr, "ERROR: Getting context from identifier failed\n");
1640     return 3;
1641   }
1642 
1643   mlirOperationDestroy(op);
1644   mlirContextDestroy(ctx);
1645 
1646   // CHECK-LABEL: @test_backreferences
1647   return 0;
1648 }
1649 
1650 /// Tests operand APIs.
1651 int testOperands() {
1652   fprintf(stderr, "@testOperands\n");
1653   // CHECK-LABEL: @testOperands
1654 
1655   MlirContext ctx = mlirContextCreate();
1656   registerAllUpstreamDialects(ctx);
1657 
1658   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("arith"));
1659   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("test"));
1660   MlirLocation loc = mlirLocationUnknownGet(ctx);
1661   MlirType indexType = mlirIndexTypeGet(ctx);
1662 
1663   // Create some constants to use as operands.
1664   MlirAttribute indexZeroLiteral =
1665       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
1666   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
1667       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
1668       indexZeroLiteral);
1669   MlirOperationState constZeroState = mlirOperationStateGet(
1670       mlirStringRefCreateFromCString("arith.constant"), loc);
1671   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
1672   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
1673   MlirOperation constZero = mlirOperationCreate(&constZeroState);
1674   MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);
1675 
1676   MlirAttribute indexOneLiteral =
1677       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
1678   MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
1679       mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
1680       indexOneLiteral);
1681   MlirOperationState constOneState = mlirOperationStateGet(
1682       mlirStringRefCreateFromCString("arith.constant"), loc);
1683   mlirOperationStateAddResults(&constOneState, 1, &indexType);
1684   mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
1685   MlirOperation constOne = mlirOperationCreate(&constOneState);
1686   MlirValue constOneValue = mlirOperationGetResult(constOne, 0);
1687 
1688   // Create the operation under test.
1689   mlirContextSetAllowUnregisteredDialects(ctx, true);
1690   MlirOperationState opState =
1691       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
1692   MlirValue initialOperands[] = {constZeroValue};
1693   mlirOperationStateAddOperands(&opState, 1, initialOperands);
1694   MlirOperation op = mlirOperationCreate(&opState);
1695 
1696   // Test operand APIs.
1697   intptr_t numOperands = mlirOperationGetNumOperands(op);
1698   fprintf(stderr, "Num Operands: %" PRIdPTR "\n", numOperands);
1699   // CHECK: Num Operands: 1
1700 
1701   MlirValue opOperand = mlirOperationGetOperand(op, 0);
1702   fprintf(stderr, "Original operand: ");
1703   mlirValuePrint(opOperand, printToStderr, NULL);
1704   // CHECK: Original operand: {{.+}} arith.constant 0 : index
1705 
1706   mlirOperationSetOperand(op, 0, constOneValue);
1707   opOperand = mlirOperationGetOperand(op, 0);
1708   fprintf(stderr, "Updated operand: ");
1709   mlirValuePrint(opOperand, printToStderr, NULL);
1710   // CHECK: Updated operand: {{.+}} arith.constant 1 : index
1711 
1712   mlirOperationDestroy(op);
1713   mlirOperationDestroy(constZero);
1714   mlirOperationDestroy(constOne);
1715   mlirContextDestroy(ctx);
1716 
1717   return 0;
1718 }
1719 
1720 /// Tests clone APIs.
1721 int testClone() {
1722   fprintf(stderr, "@testClone\n");
1723   // CHECK-LABEL: @testClone
1724 
1725   MlirContext ctx = mlirContextCreate();
1726   registerAllUpstreamDialects(ctx);
1727 
1728   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));
1729   MlirLocation loc = mlirLocationUnknownGet(ctx);
1730   MlirType indexType = mlirIndexTypeGet(ctx);
1731   MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");
1732 
1733   MlirAttribute indexZeroLiteral =
1734       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
1735   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
1736       mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
1737   MlirOperationState constZeroState = mlirOperationStateGet(
1738       mlirStringRefCreateFromCString("arith.constant"), loc);
1739   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
1740   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
1741   MlirOperation constZero = mlirOperationCreate(&constZeroState);
1742 
1743   MlirAttribute indexOneLiteral =
1744       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
1745   MlirOperation constOne = mlirOperationClone(constZero);
1746   mlirOperationSetAttributeByName(constOne, valueStringRef, indexOneLiteral);
1747 
1748   mlirOperationPrint(constZero, printToStderr, NULL);
1749   mlirOperationPrint(constOne, printToStderr, NULL);
1750   // CHECK: arith.constant 0 : index
1751   // CHECK: arith.constant 1 : index
1752 
1753   mlirOperationDestroy(constZero);
1754   mlirOperationDestroy(constOne);
1755   mlirContextDestroy(ctx);
1756   return 0;
1757 }
1758 
1759 // Wraps a diagnostic into additional text we can match against.
1760 MlirLogicalResult errorHandler(MlirDiagnostic diagnostic, void *userData) {
1761   fprintf(stderr, "processing diagnostic (userData: %" PRIdPTR ") <<\n",
1762           (intptr_t)userData);
1763   mlirDiagnosticPrint(diagnostic, printToStderr, NULL);
1764   fprintf(stderr, "\n");
1765   MlirLocation loc = mlirDiagnosticGetLocation(diagnostic);
1766   mlirLocationPrint(loc, printToStderr, NULL);
1767   assert(mlirDiagnosticGetNumNotes(diagnostic) == 0);
1768   fprintf(stderr, "\n>> end of diagnostic (userData: %" PRIdPTR ")\n",
1769           (intptr_t)userData);
1770   return mlirLogicalResultSuccess();
1771 }
1772 
1773 // Logs when the delete user data callback is called
1774 static void deleteUserData(void *userData) {
1775   fprintf(stderr, "deleting user data (userData: %" PRIdPTR ")\n",
1776           (intptr_t)userData);
1777 }
1778 
1779 int testTypeID(MlirContext ctx) {
1780   fprintf(stderr, "@testTypeID\n");
1781 
1782   // Test getting and comparing type and attribute type ids.
1783   MlirType i32 = mlirIntegerTypeGet(ctx, 32);
1784   MlirTypeID i32ID = mlirTypeGetTypeID(i32);
1785   MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
1786   MlirTypeID ui32ID = mlirTypeGetTypeID(ui32);
1787   MlirType f32 = mlirF32TypeGet(ctx);
1788   MlirTypeID f32ID = mlirTypeGetTypeID(f32);
1789   MlirAttribute i32Attr = mlirIntegerAttrGet(i32, 1);
1790   MlirTypeID i32AttrID = mlirAttributeGetTypeID(i32Attr);
1791 
1792   if (mlirTypeIDIsNull(i32ID) || mlirTypeIDIsNull(ui32ID) ||
1793       mlirTypeIDIsNull(f32ID) || mlirTypeIDIsNull(i32AttrID)) {
1794     fprintf(stderr, "ERROR: Expected type ids to be present\n");
1795     return 1;
1796   }
1797 
1798   if (!mlirTypeIDEqual(i32ID, ui32ID) ||
1799       mlirTypeIDHashValue(i32ID) != mlirTypeIDHashValue(ui32ID)) {
1800     fprintf(
1801         stderr,
1802         "ERROR: Expected different integer types to have the same type id\n");
1803     return 2;
1804   }
1805 
1806   if (mlirTypeIDEqual(i32ID, f32ID)) {
1807     fprintf(stderr,
1808             "ERROR: Expected integer type id to not equal float type id\n");
1809     return 3;
1810   }
1811 
1812   if (mlirTypeIDEqual(i32ID, i32AttrID)) {
1813     fprintf(stderr, "ERROR: Expected integer type id to not equal integer "
1814                     "attribute type id\n");
1815     return 4;
1816   }
1817 
1818   MlirLocation loc = mlirLocationUnknownGet(ctx);
1819   MlirType indexType = mlirIndexTypeGet(ctx);
1820   MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");
1821 
1822   // Create a registered operation, which should have a type id.
1823   MlirAttribute indexZeroLiteral =
1824       mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
1825   MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
1826       mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
1827   MlirOperationState constZeroState = mlirOperationStateGet(
1828       mlirStringRefCreateFromCString("arith.constant"), loc);
1829   mlirOperationStateAddResults(&constZeroState, 1, &indexType);
1830   mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
1831   MlirOperation constZero = mlirOperationCreate(&constZeroState);
1832 
1833   if (!mlirOperationVerify(constZero)) {
1834     fprintf(stderr, "ERROR: Expected operation to verify correctly\n");
1835     return 5;
1836   }
1837 
1838   if (mlirOperationIsNull(constZero)) {
1839     fprintf(stderr, "ERROR: Expected registered operation to be present\n");
1840     return 6;
1841   }
1842 
1843   MlirTypeID registeredOpID = mlirOperationGetTypeID(constZero);
1844 
1845   if (mlirTypeIDIsNull(registeredOpID)) {
1846     fprintf(stderr,
1847             "ERROR: Expected registered operation type id to be present\n");
1848     return 7;
1849   }
1850 
1851   // Create an unregistered operation, which should not have a type id.
1852   mlirContextSetAllowUnregisteredDialects(ctx, true);
1853   MlirOperationState opState =
1854       mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
1855   MlirOperation unregisteredOp = mlirOperationCreate(&opState);
1856   if (mlirOperationIsNull(unregisteredOp)) {
1857     fprintf(stderr, "ERROR: Expected unregistered operation to be present\n");
1858     return 8;
1859   }
1860 
1861   MlirTypeID unregisteredOpID = mlirOperationGetTypeID(unregisteredOp);
1862 
1863   if (!mlirTypeIDIsNull(unregisteredOpID)) {
1864     fprintf(stderr,
1865             "ERROR: Expected unregistered operation type id to be null\n");
1866     return 9;
1867   }
1868 
1869   mlirOperationDestroy(constZero);
1870   mlirOperationDestroy(unregisteredOp);
1871 
1872   return 0;
1873 }
1874 
1875 int testSymbolTable(MlirContext ctx) {
1876   fprintf(stderr, "@testSymbolTable\n");
1877 
1878   const char *moduleString = "func.func private @foo()"
1879                              "func.func private @bar()";
1880   const char *otherModuleString = "func.func private @qux()"
1881                                   "func.func private @foo()";
1882 
1883   MlirModule module =
1884       mlirModuleCreateParse(ctx, mlirStringRefCreateFromCString(moduleString));
1885   MlirModule otherModule = mlirModuleCreateParse(
1886       ctx, mlirStringRefCreateFromCString(otherModuleString));
1887 
1888   MlirSymbolTable symbolTable =
1889       mlirSymbolTableCreate(mlirModuleGetOperation(module));
1890 
1891   MlirOperation funcFoo =
1892       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("foo"));
1893   if (mlirOperationIsNull(funcFoo))
1894     return 1;
1895 
1896   MlirOperation funcBar =
1897       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
1898   if (mlirOperationEqual(funcFoo, funcBar))
1899     return 2;
1900 
1901   MlirOperation missing =
1902       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
1903   if (!mlirOperationIsNull(missing))
1904     return 3;
1905 
1906   MlirBlock moduleBody = mlirModuleGetBody(module);
1907   MlirBlock otherModuleBody = mlirModuleGetBody(otherModule);
1908   MlirOperation operation = mlirBlockGetFirstOperation(otherModuleBody);
1909   mlirOperationRemoveFromParent(operation);
1910   mlirBlockAppendOwnedOperation(moduleBody, operation);
1911 
1912   // At this moment, the operation is still missing from the symbol table.
1913   MlirOperation stillMissing =
1914       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
1915   if (!mlirOperationIsNull(stillMissing))
1916     return 4;
1917 
1918   // After it is added to the symbol table, and not only the operation with
1919   // which the table is associated, it can be looked up.
1920   mlirSymbolTableInsert(symbolTable, operation);
1921   MlirOperation funcQux =
1922       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
1923   if (!mlirOperationEqual(operation, funcQux))
1924     return 5;
1925 
1926   // Erasing from the symbol table also removes the operation.
1927   mlirSymbolTableErase(symbolTable, funcBar);
1928   MlirOperation nowMissing =
1929       mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
1930   if (!mlirOperationIsNull(nowMissing))
1931     return 6;
1932 
1933   // Adding a symbol with the same name to the table should rename.
1934   MlirOperation duplicateNameOp = mlirBlockGetFirstOperation(otherModuleBody);
1935   mlirOperationRemoveFromParent(duplicateNameOp);
1936   mlirBlockAppendOwnedOperation(moduleBody, duplicateNameOp);
1937   MlirAttribute newName = mlirSymbolTableInsert(symbolTable, duplicateNameOp);
1938   MlirStringRef newNameStr = mlirStringAttrGetValue(newName);
1939   if (mlirStringRefEqual(newNameStr, mlirStringRefCreateFromCString("foo")))
1940     return 7;
1941   MlirAttribute updatedName = mlirOperationGetAttributeByName(
1942       duplicateNameOp, mlirSymbolTableGetSymbolAttributeName());
1943   if (!mlirAttributeEqual(updatedName, newName))
1944     return 8;
1945 
1946   mlirOperationDump(mlirModuleGetOperation(module));
1947   mlirOperationDump(mlirModuleGetOperation(otherModule));
1948   // clang-format off
1949   // CHECK-LABEL: @testSymbolTable
1950   // CHECK: module
1951   // CHECK:   func private @foo
1952   // CHECK:   func private @qux
1953   // CHECK:   func private @foo{{.+}}
1954   // CHECK: module
1955   // CHECK-NOT: @qux
1956   // CHECK-NOT: @foo
1957   // clang-format on
1958 
1959   mlirSymbolTableDestroy(symbolTable);
1960   mlirModuleDestroy(module);
1961   mlirModuleDestroy(otherModule);
1962 
1963   return 0;
1964 }
1965 
1966 int testDialectRegistry() {
1967   fprintf(stderr, "@testDialectRegistry\n");
1968 
1969   MlirDialectRegistry registry = mlirDialectRegistryCreate();
1970   if (mlirDialectRegistryIsNull(registry)) {
1971     fprintf(stderr, "ERROR: Expected registry to be present\n");
1972     return 1;
1973   }
1974 
1975   MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();
1976   mlirDialectHandleInsertDialect(stdHandle, registry);
1977 
1978   MlirContext ctx = mlirContextCreate();
1979   if (mlirContextGetNumRegisteredDialects(ctx) != 0) {
1980     fprintf(stderr,
1981             "ERROR: Expected no dialects to be registered to new context\n");
1982   }
1983 
1984   mlirContextAppendDialectRegistry(ctx, registry);
1985   if (mlirContextGetNumRegisteredDialects(ctx) != 1) {
1986     fprintf(stderr, "ERROR: Expected the dialect in the registry to be "
1987                     "registered to the context\n");
1988   }
1989 
1990   mlirContextDestroy(ctx);
1991   mlirDialectRegistryDestroy(registry);
1992 
1993   return 0;
1994 }
1995 
1996 void testDiagnostics() {
1997   MlirContext ctx = mlirContextCreate();
1998   MlirDiagnosticHandlerID id = mlirContextAttachDiagnosticHandler(
1999       ctx, errorHandler, (void *)42, deleteUserData);
2000   fprintf(stderr, "@test_diagnostics\n");
2001   MlirLocation unknownLoc = mlirLocationUnknownGet(ctx);
2002   mlirEmitError(unknownLoc, "test diagnostics");
2003   MlirLocation fileLineColLoc = mlirLocationFileLineColGet(
2004       ctx, mlirStringRefCreateFromCString("file.c"), 1, 2);
2005   mlirEmitError(fileLineColLoc, "test diagnostics");
2006   MlirLocation callSiteLoc = mlirLocationCallSiteGet(
2007       mlirLocationFileLineColGet(
2008           ctx, mlirStringRefCreateFromCString("other-file.c"), 2, 3),
2009       fileLineColLoc);
2010   mlirEmitError(callSiteLoc, "test diagnostics");
2011   MlirLocation null = {0};
2012   MlirLocation nameLoc =
2013       mlirLocationNameGet(ctx, mlirStringRefCreateFromCString("named"), null);
2014   mlirEmitError(nameLoc, "test diagnostics");
2015   MlirLocation locs[2] = {nameLoc, callSiteLoc};
2016   MlirAttribute nullAttr = {0};
2017   MlirLocation fusedLoc = mlirLocationFusedGet(ctx, 2, locs, nullAttr);
2018   mlirEmitError(fusedLoc, "test diagnostics");
2019   mlirContextDetachDiagnosticHandler(ctx, id);
2020   mlirEmitError(unknownLoc, "more test diagnostics");
2021   // CHECK-LABEL: @test_diagnostics
2022   // CHECK: processing diagnostic (userData: 42) <<
2023   // CHECK:   test diagnostics
2024   // CHECK:   loc(unknown)
2025   // CHECK: >> end of diagnostic (userData: 42)
2026   // CHECK: processing diagnostic (userData: 42) <<
2027   // CHECK:   test diagnostics
2028   // CHECK:   loc("file.c":1:2)
2029   // CHECK: >> end of diagnostic (userData: 42)
2030   // CHECK: processing diagnostic (userData: 42) <<
2031   // CHECK:   test diagnostics
2032   // CHECK:   loc(callsite("other-file.c":2:3 at "file.c":1:2))
2033   // CHECK: >> end of diagnostic (userData: 42)
2034   // CHECK: processing diagnostic (userData: 42) <<
2035   // CHECK:   test diagnostics
2036   // CHECK:   loc("named")
2037   // CHECK: >> end of diagnostic (userData: 42)
2038   // CHECK: processing diagnostic (userData: 42) <<
2039   // CHECK:   test diagnostics
2040   // CHECK:   loc(fused["named", callsite("other-file.c":2:3 at "file.c":1:2)])
2041   // CHECK: deleting user data (userData: 42)
2042   // CHECK-NOT: processing diagnostic
2043   // CHECK:     more test diagnostics
2044   mlirContextDestroy(ctx);
2045 }
2046 
2047 int main() {
2048   MlirContext ctx = mlirContextCreate();
2049   registerAllUpstreamDialects(ctx);
2050   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));
2051   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("memref"));
2052   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("shape"));
2053   mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("scf"));
2054 
2055   if (constructAndTraverseIr(ctx))
2056     return 1;
2057   buildWithInsertionsAndPrint(ctx);
2058   if (createOperationWithTypeInference(ctx))
2059     return 2;
2060 
2061   if (printBuiltinTypes(ctx))
2062     return 3;
2063   if (printBuiltinAttributes(ctx))
2064     return 4;
2065   if (printAffineMap(ctx))
2066     return 5;
2067   if (printAffineExpr(ctx))
2068     return 6;
2069   if (affineMapFromExprs(ctx))
2070     return 7;
2071   if (printIntegerSet(ctx))
2072     return 8;
2073   if (registerOnlyStd())
2074     return 9;
2075   if (testBackreferences())
2076     return 10;
2077   if (testOperands())
2078     return 11;
2079   if (testClone())
2080     return 12;
2081   if (testTypeID(ctx))
2082     return 13;
2083   if (testSymbolTable(ctx))
2084     return 14;
2085   if (testDialectRegistry())
2086     return 15;
2087 
2088   mlirContextDestroy(ctx);
2089 
2090   testDiagnostics();
2091   return 0;
2092 }
2093