[PATCH] D99474: [OCaml] Code simplification using string allocation functions

Josh Berdine via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sun Mar 28 15:32:17 PDT 2021


jberdine created this revision.
jberdine added a reviewer: vaivaswatha.
Herald added a reviewer: whitequark.
jberdine requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Using the `cstr_to_string` function that allocates and initializes an
OCaml `string` value enables simplifications in several cases. This
change also has the effect of avoiding calling `memcpy` on NULL
pointers even if only 0 bytes are to be copied.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D99474

Files:
  llvm/bindings/ocaml/llvm/llvm_ocaml.c


Index: llvm/bindings/ocaml/llvm/llvm_ocaml.c
===================================================================
--- llvm/bindings/ocaml/llvm/llvm_ocaml.c
+++ llvm/bindings/ocaml/llvm/llvm_ocaml.c
@@ -279,18 +279,14 @@
 CAMLprim value llvm_get_string_attr_kind(LLVMAttributeRef A) {
   unsigned Length;
   const char *String = LLVMGetStringAttributeKind(A, &Length);
-  value Result = caml_alloc_string(Length);
-  memcpy((char *)String_val(Result), String, Length);
-  return Result;
+  return cstr_to_string (String, Length);
 }
 
 /* llattribute -> string */
 CAMLprim value llvm_get_string_attr_value(LLVMAttributeRef A) {
   unsigned Length;
   const char *String = LLVMGetStringAttributeValue(A, &Length);
-  value Result = caml_alloc_string(Length);
-  memcpy((char *)String_val(Result), String, Length);
-  return Result;
+  return cstr_to_string (String, Length);
 }
 
 /*===-- Modules -----------------------------------------------------------===*/
@@ -2512,11 +2508,9 @@
 
 /* llmemorybuffer -> string */
 CAMLprim value llvm_memorybuffer_as_string(LLVMMemoryBufferRef MemBuf) {
-  value String = caml_alloc_string(LLVMGetBufferSize(MemBuf));
-  memcpy((char *)String_val(String), LLVMGetBufferStart(MemBuf),
-         LLVMGetBufferSize(MemBuf));
-
-  return String;
+  size_t BufferSize = LLVMGetBufferSize(MemBuf);
+  const char *BufferStart = LLVMGetBufferStart(MemBuf);
+  return cstr_to_string(BufferStart, BufferSize);
 }
 
 /* llmemorybuffer -> unit */


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D99474.333741.patch
Type: text/x-patch
Size: 1472 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20210328/33e66cc8/attachment.bin>


More information about the llvm-commits mailing list