Skip to content

Commit b82a102

Browse files
ivanmurashkoxlauko
authored andcommitted
[CIR][CodeGen] Support trailing_zeros for constant string literals (llvm#617)
The patch resolves [issue llvm#248](llvm/clangir#248). It can be considered a subsequent patch to [llvm#373](llvm/clangir#373), where the case of empty strings was processed. The new patch adds processing for non-empty strings that may contain trailing zeros, such as: ``` char big_string[100000] = "123"; ``` That is converted to ``` @big_string = #cir.const_array<"123" : !cir.array<!s8i x 3>, trailing_zeros> : !cir.array<!s8i x 100000> ```
1 parent b5e1f59 commit b82a102

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

clang/lib/CIR/CodeGen/CIRGenBuilder.h

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,15 +153,26 @@ class CIRGenBuilderTy : public CIRBaseBuilderTy {
153153
unsigned size = 0) {
154154
unsigned finalSize = size ? size : str.size();
155155

156+
size_t lastNonZeroPos = str.find_last_not_of('\0');
156157
// If the string is full of null bytes, emit a #cir.zero rather than
157158
// a #cir.const_array.
158-
if (str.count('\0') == str.size()) {
159+
if (lastNonZeroPos == llvm::StringRef::npos) {
159160
auto arrayTy = mlir::cir::ArrayType::get(getContext(), eltTy, finalSize);
160161
return getZeroAttr(arrayTy);
161162
}
162-
163-
auto arrayTy = mlir::cir::ArrayType::get(getContext(), eltTy, finalSize);
164-
return getConstArray(mlir::StringAttr::get(str, arrayTy), arrayTy);
163+
// We will use trailing zeros only if there are more than one zero
164+
// at the end
165+
int trailingZerosNum =
166+
finalSize > lastNonZeroPos + 2 ? finalSize - lastNonZeroPos - 1 : 0;
167+
auto truncatedArrayTy = mlir::cir::ArrayType::get(
168+
getContext(), eltTy, finalSize - trailingZerosNum);
169+
auto fullArrayTy =
170+
mlir::cir::ArrayType::get(getContext(), eltTy, finalSize);
171+
return mlir::cir::ConstArrayAttr::get(
172+
getContext(), fullArrayTy,
173+
mlir::StringAttr::get(str.drop_back(trailingZerosNum),
174+
truncatedArrayTy),
175+
trailingZerosNum);
165176
}
166177

167178
mlir::cir::ConstArrayAttr getConstArray(mlir::Attribute attrs,

0 commit comments

Comments
 (0)