Using TypeStorage idiom as given in Toy Ch7

Hi:
I have a small qs relating to how ArrayRef is used in storing information w.r.t mlir::TypeStorage.

I am trying to follow the idiom for type creation as given in llvm-project/Dialect.cpp at main · llvm/llvm-project · GitHub
On that line we are using ‘llvm::ArrayRef’ used to store type information for the created type.
But as ArrayRef is just a pointer to some memory, where is this buffer allocated ? Does it count on calling code to keep the array alive ?
Thanks

If you look a few lines above, the ArrayRef is copied into the storage allocator that was provided when constructing the storage instance. This keeps the data live for the duration of the storage instance.

– River

Thanks. I just wasn’t sure if copyTo actually did the allocation.
Follow on qs:
If my custom type, with MyTensorTypeStorage has two fields e.g.

struct MyTensorTypeStorage : public mlir::TypeStorage {
  using KeyTy = std::tuple<llvm::ArrayRef<uint64_t>, mlir::Type>;

  MyTensorTypeStorage(llvm::ArrayRef<uint64_t> shape, mlir::Type elementType)
      : shape(shape), elementType(elementType) {}
   ...
   llvm::ArrayRef<uint64_t> shape;
   mlir::Type  elementType;
};

Then would this code be correct for it :

const MyTensorTypeStorage *  
construct(mlir::TypeStorageAllocator &allocator, const KeyTy &key) {

    return new (allocator.allocate<MyTensorTypeStorage>())
        MyTensorTypeStorage(allocator.copyInto(std::get<0>(key)),
                                std::get<1>(key));
  }

My doubt is the last part 'std::get<1>(key). Do I need to do something like allocator.copyInto(std::get<1>(key) as well?

You only really need to copy into the allocator if the parameter “references” something with a lifetime that isn’t guaranteed to be at least as long as the new type storage instance. For ArrayRef, you need to allocate because it generally contains a pointer to some temporary data (often stack allocated). Type, on the other hand, points to data that is guaranteed to outlive your type storage instance, so you don’t need to copy anything for it.

– River

Thank you so much for the clarification :slight_smile: