mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-09-24 22:02:23 +01:00
Switch to BumpPtrAllocator for C-string storage (#6550)
This keeps the allocations cheap and simplifies the code. It was inspired by the need to expand param files, but no functionality changed yet.
This commit is contained in:
@@ -18,6 +18,7 @@
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include "llvm/ADT/StringRef.h"
|
||||
#include "llvm/Support/Allocator.h"
|
||||
#include "llvm/Support/ConvertUTF.h"
|
||||
|
||||
namespace Carbon {
|
||||
@@ -211,33 +212,19 @@ auto StringRefContainsPointer(llvm::StringRef ref, const char* ptr) -> bool {
|
||||
|
||||
auto BuildCStrArgs(llvm::StringRef tool_path,
|
||||
llvm::ArrayRef<llvm::StringRef> args,
|
||||
llvm::OwningArrayRef<char>& cstr_arg_storage)
|
||||
llvm::BumpPtrAllocator& alloc)
|
||||
-> llvm::SmallVector<const char*, 64> {
|
||||
return BuildCStrArgs(tool_path, /*prefix_args=*/{}, args, cstr_arg_storage);
|
||||
return BuildCStrArgs(tool_path, /*prefix_args=*/{}, args, alloc);
|
||||
}
|
||||
|
||||
auto BuildCStrArgs(llvm::StringRef tool_path,
|
||||
llvm::ArrayRef<std::string> prefix_args,
|
||||
llvm::ArrayRef<llvm::StringRef> args,
|
||||
llvm::OwningArrayRef<char>& cstr_arg_storage)
|
||||
llvm::BumpPtrAllocator& alloc)
|
||||
-> llvm::SmallVector<const char*, 64> {
|
||||
// Render the arguments into null-terminated C-strings. Command lines can get
|
||||
// quite long in build systems so this tries to minimize the memory allocation
|
||||
// overhead.
|
||||
|
||||
// Precompute the total C-string data size needed.
|
||||
int total_size = tool_path.size() + 1;
|
||||
for (llvm::StringRef arg : args) {
|
||||
// Accumulate both the string size and a null terminator byte.
|
||||
total_size += arg.size() + 1;
|
||||
}
|
||||
|
||||
// Allocate one chunk of storage for the actual C-strings, and reserve a
|
||||
// vector of pointers into the storage.
|
||||
cstr_arg_storage = llvm::OwningArrayRef<char>(total_size);
|
||||
ssize_t i = 0;
|
||||
auto make_cstr = [&](llvm::StringRef arg) {
|
||||
char* cstr = &cstr_arg_storage[i];
|
||||
char* cstr = alloc.Allocate<char>(arg.size() + 1);
|
||||
memcpy(cstr, arg.data(), arg.size());
|
||||
cstr[arg.size()] = '\0';
|
||||
i += arg.size() + 1;
|
||||
|
||||
Reference in New Issue
Block a user